Android Java app fails to send selected file/data via Bluetooth - java

My current android app can turn on Bluetooth, make itself discoverable, list paired devices, and select a file from the device ( ie an image). However when I attempted to hit "send" the app seems to crash with an error. Not sure if it's refusing to send, or if it's not actually obtaining the file (yesterday I had a problem where it refused to send the selected, saying for me to select a file repeatedly. I will post the crash results and my mainActivity code. If anyone suggestions or ideas, please let me know.
Error: Debugging device
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bluetooth_demoproject, PID: 17593
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=300, data=null} to activity {com.example.bluetooth_demoproject/com.example.bluetooth_demoproject.MainActivity}: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.app.ActivityThread.deliverResults(ActivityThread.java:4107)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6120)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/Screenshots/Screenshot_20161013-215137.png exposed beyond app through ClipData.Item.getUri()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
at android.net.Uri.checkFileUriExposed(Uri.java:2346)
at android.content.ClipData.prepareToLeaveProcess(ClipData.java:832)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8909)
at android.content.Intent.prepareToLeaveProcess(Intent.java:8894)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1517)
at android.app.Activity.startActivityForResult(Activity.java:4224)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.app.Activity.startActivity(Activity.java:4507)
at android.app.Activity.startActivity(Activity.java:4475)
at com.example.bluetooth_demoproject.MainActivity.onActivityResult(MainActivity.java:350)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4103)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4150) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6120) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Disconnected from the target VM, address: 'localhost:8601', transport: 'socket'
Here is my MainActivity
package com.example.bluetooth_demoproject;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends Activity {
// Creating objects -----------------------------
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_BLU = 1;
// private static final int REQUEST_DISCOVER_BT_ = 1;
private static int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
TextView mBluetoothStatus, mPairedDevicesList, mTextFolder;
ImageView mBluetoothIcon;
Button mOnButton, mDiscoverableButton, mPairedDevices, mbuttonOpenDialog, msendBluetooth, mbuttonUp;
File root, fileroot, curFolder;
EditText dataPath;
private static final int DISCOVER_DURATION = 300;
private List<String> fileList = new ArrayList<String>();
// -------------------------------------------------------
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataPath =(EditText)findViewById(R.id.FilePath);
mTextFolder = findViewById(R.id.folder);
mBluetoothStatus = findViewById(R.id.BluetoothStatus);
mBluetoothIcon = findViewById(R.id.bluetoothIcon);
mOnButton = findViewById(R.id.onButton);
// mOffButton = findViewById(R.id.offButton);
mDiscoverableButton = findViewById(R.id.discoverableButton);
mPairedDevices = findViewById(R.id.pairedDevices);
mPairedDevicesList = findViewById(R.id.pairedDeviceList);
mbuttonOpenDialog = findViewById(R.id.opendailog);
msendBluetooth = findViewById(R.id.sendBluetooth);
mbuttonUp = findViewById(R.id.up);
mbuttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dataPath.setText("");
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new
File(Environment.getExternalStorageDirectory().getAbsolutePath());
curFolder = root;
msendBluetooth.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
sendViaBluetooth();
}
});
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBlueAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable it
if (!mBlueAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//set image according to bluetooth Status
if (mBlueAdapter.isEnabled()) {
mBluetoothIcon.setImageResource(R.drawable.action_on);
}
else {
mBluetoothIcon.setImageResource(R.drawable.action_off);
}
//on button Click
mOnButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()) {
showToast("Turning Bluetooth on...");
// intent to on bluetooth
Intent intent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover Bluetooth button
mDiscoverableButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (!mBlueAdapter.isDiscovering()) {
showToast("Making device discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_BLU);
}
}
});
// off button click
// mOffButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (mBlueAdapter.isEnabled()) {
// showToast("Turning Bluetooth off...");
// // intent to turn off bluetooth
// mBluetoothIcon.setImageResource(R.drawable.action_off);
// }
// else{
// showToast("Bluetooth is already off");
// }
//
// }
//});
//get paired device button click
mPairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()) {
mPairedDevices.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device : devices){
mPairedDevices.append("\nDevice: " + device.getName() + "," + device );
}
}
else {
//bluetooth is off and cant get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
// #Override
// protected void onPrepareDialog(int id, Dialog dialog) {
// super.onPrepareDialog(id, dialog);
// switch (id) {
// case CUSTOM_DIALOG_ID:
// ListDir(curFolder);
// break;
// }
// }
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == CUSTOM_DIALOG_ID) {
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dailoglayout);
dialog.setTitle("Select Files");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
mTextFolder = (TextView) dialog.findViewById(R.id.folder);
mbuttonUp = (Button) dialog.findViewById(R.id.up);
mbuttonUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListDir(curFolder.getParentFile());
}
});
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File selected = new File(fileList.get(position));
if (selected.isDirectory()) {
ListDir(selected);
}
else if (selected.isFile()) {
getSelectedFile(selected);
}
else {
dismissDialog(CUSTOM_DIALOG_ID);
}
}
});
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == CUSTOM_DIALOG_ID) {
ListDir(curFolder);
}
}
public void getSelectedFile(File f) {
dataPath.setText(f.getAbsolutePath());
fileList.clear();
dismissDialog(CUSTOM_DIALOG_ID);
}
public void ListDir(File f) {
if (f.equals(root)) {
mbuttonUp.setEnabled(false);
}
else {
mbuttonUp.setEnabled(true);
}
curFolder = f;
mTextFolder.setText(f.getAbsolutePath());
dataPath.setText(f.getAbsolutePath());
File[] files = f.listFiles();
fileList.clear();
for (File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
// exits to app --------------------------------
public void exit(View V) {
mBlueAdapter.disable();
Toast.makeText(this, "*** Now bluetooth is off...", Toast.LENGTH_LONG).show();
finish();
}
// send file via bluetooth ------------------------
public void sendViaBluetooth() {
if(!dataPath.equals(null)) {
if(mBlueAdapter == null) {
Toast.makeText(this, "Device doesnt support bluetooth", Toast.LENGTH_LONG).show();
}
else {
enableBluetooth();
}
}
else {
Toast.makeText(this, "please select a file", Toast.LENGTH_LONG).show();
}
}
public void enableBluetooth() {
showToast("Making device discoverable");
Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoveryIntent, REQUEST_BLU);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU) {
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);// STOPPED HERE-----------------------------------------------------------------
i.setType("*/*");
File file = new File(dataPath.getText().toString());
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(i, 0);
if (list.size() > 0) {
String packageName = null;
String className = null;
boolean found = false;
for (ResolveInfo info : list) {
packageName = info.activityInfo.packageName;
if (packageName.equals("com.android.bluetooth")) {
className = info.activityInfo.name;
found = true;
break;
}
}
//CHECK BLUETOOTH available or not------------------------------------------------
if (!found) {
Toast.makeText(this, "Bluetooth not been found", Toast.LENGTH_LONG).show();
} else {
i.setClassName(packageName, className);
startActivity(i);
}
}
} else {
Toast.makeText(this, "Bluetooth is cancelled", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// Toast.makeText(this, "**********************************\nDeveloper: www.santoshkumarsingh.com\n**********************************", Toast.LENGTH_LONG).show();
// return true;
// }
return super.onOptionsItemSelected(item);
}
//toast message function
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT) .show();
}
}

You have trouble with file exchange not with BLE.
Did you ever read Android FileUriExposedException?

Related

what is the 101 error code mean in in-app-billing v3 library?

I am using in app billing v3 library, it is always get error
and error code is 101
What does this error code mean?
some details:
I am a developer working from Palestine and working on an app uploadded on Indian google play account
I created activity that included three buttons to purchase remove Ads
-the first button to subscribe one month
-the second to subscribe one year
-the third to purchase lifetime
I used this library 'com.anjlab.android.iab.v3:library:1.0.44'
I created product in google play console and its name PRODUCT_ID
this product will purchased when user click on button lifeTime
and I created two subscriptions
-the first's name is SUBSCRIPTION_MONTH_ID
and will be purchased when the user click on oneMonth button
-the second's name is SUBSCRIPTION_YEAR_ID
and will be purchased when the user click on oneYear button
this the code that I used
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.TransactionDetails;
public class InAppBilling extends AppCompatActivity{
BillingProcessor bp;
private static final String PRODUCT_ID = "****";
private static final String SUBSCRIPTION_MONTH_ID = "***";
private static final String SUBSCRIPTION_YEAR_ID = "***";
private static final String LICENSE_KEY = "*****";
private static final String MERCHANT_ID = "**";
Button oneMonth, oneYear, lifeTime;
int flag;
String android_id;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_app_purchase);
flag = 0;
android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
final Toolbar toolbar = findViewById(R.id.toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setTitle("Remove Ads");
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
if(!BillingProcessor.isIabServiceAvailable(this)) {
Toast.makeText(this, "In-app billing service is unavailable, please upgrade Android Market/Play to version >= 3.9.16", Toast.LENGTH_SHORT).show();
}
bp = new BillingProcessor(this, LICENSE_KEY, MERCHANT_ID, new BillingProcessor.IBillingHandler() {
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
Toast.makeText(InAppBilling.this, "successfully purchased, restart the app please", Toast.LENGTH_SHORT).show();
}
#Override
public void onBillingError(int errorCode, Throwable error) {
Toast.makeText(InAppBilling.this, "Error Billing", Toast.LENGTH_SHORT).show();
Log.e("nourbilling", "onBillingError: errorCode: "+errorCode+" error: "+error);
}
#Override
public void onBillingInitialized() {
}
#Override
public void onPurchaseHistoryRestored() {
for(String sku : bp.listOwnedProducts())
Log.d("nourbilling", "Owned Managed Product: " + sku);
for(String sku : bp.listOwnedSubscriptions())
Log.d("nourbilling", "Owned Subscription: " + sku);
}
});
oneMonth = findViewById(R.id.oneMonth);
oneYear = findViewById(R.id.oneYear);
lifeTime = findViewById(R.id.lifetime);
final Activity activity = this;
oneMonth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
createDialog(savedInstanceState, activity).show();
}
});
oneYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 2;
createDialog(savedInstanceState, activity).show();
}
});
lifeTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 3;
createDialog(savedInstanceState, activity).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data))
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
if (bp != null)
bp.release();
super.onDestroy();
}
public Dialog createDialog(Bundle savedInstanceState, final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("are you sure to remove ads by billing?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (flag == 1) {
bp.subscribe(activity, SUBSCRIPTION_MONTH_ID);
} else if (flag == 2) {
bp.subscribe(activity, SUBSCRIPTION_YEAR_ID);
} else if (flag == 3) {
bp.purchase(activity, PRODUCT_ID);
}
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
can you help me, please?

Android app crashes before intent is launched

I'm creating my first android app, so I'm really a beginner with (android) development.
The first fase of the app is to implement an Activity (i.e. BleActivity.java), which is called when a certain button is clicked. The BleActivity should list available BLE devices (testing with a tiSensorTag CC2650) and later on I want to read the data from the devices.
It was quite a challenge to get it to work because most of the tutorials online are written with deprecated API's. After combining several tutorials, the app is now working!
There is one bug in the app which I'm unable to fix:
When bluetooth is turned off and I trigger the BleActivity, the onResume() checks if bluetooth is enabled (which is not the case) and if it's not, a dialog screen appears requesting the user to turn bluetooth on.
I can see the dialog screen but before I'm able to use it, the app crashes.
BleActivity.java
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class BleActivity extends ListActivity {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
// see nested class LeDeviceListAdapter
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 10000;
private Handler mHandler;
private boolean mScanning;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private static final String INFO = "ZINFO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check if BLE is supported
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
} else {
Log.i(INFO, "onCreate: BLE is supported");
}
// Create a Handler to send and process Message Class and Runnable objects associated with a thread's MessageQueue.
mHandler = new Handler();
// Get BluetoothManager and BluetoothAdapter in order to conduct overall Bluetooth Management.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
#Override
protected void onResume() {
super.onResume();
// Initialize list view adapter
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
//Check if permission for ACCESS_COARSE_LOCATION (AndroidManifest.xml) is granted.
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.grant_permission, Toast.LENGTH_LONG).show();
finish();
} else {
Log.i(INFO, "onResume: Permission for ACCESS_COARSE_LOCATION is granted");
}
}
// Check if bluetoothAdapter is successfully obtained and if BLE is enabled.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
Log.i(INFO, "onResume: BLE is enabled");
}
// GET getBluetoothLeScanner(): This class provides methods to perform scan related operations for Bluetooth LE devices
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
// Set scan settings
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
// Set device filter (null is allowed)
filters = new ArrayList<ScanFilter>();
// START SCAN FOR BLE DEVICES!
scanLeDevice(true);
}
// When user denies prompt for enabling Bluetooth, the Activity is closed
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
// Pause scanning for BLE devices */
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
//Methods for permission check
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(BleActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission. ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(INFO, "onRequestPermissionsResult: PERMISSION_GRANTED");
} else {
finish();
}
}
}
}
// Methods for START & STOP scan
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mLEScanner.stopScan(mScanCallback); //STOP SCANNING
}
}, SCAN_PERIOD); // Stops scanning after a pre-defined scan period.
mScanning = true;
mLEScanner.startScan(filters, settings, mScanCallback); //START SCANNING
} else {
mScanning = false;
mLEScanner.stopScan(mScanCallback); //STOP SCANNING
}
if(mScanning == true) {
//TODO: Implement code for when the app is scanning (green stoplight, turning wheel, etc.)
} else {
//TODO: Implement code for when the app is NOT scanning (red stoplight, idle wheel, etc.)
}
}
// Bluetooth LE scan results are reported using these callbacks.
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice btDevice = result.getDevice();
mLeDeviceListAdapter.addDevice(btDevice);
mLeDeviceListAdapter.notifyDataSetChanged(); }
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult - Results", sr.toString());
}
}
#Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
// ListAdapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = BleActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
/*
TODO: implement onListItemClick (see example code)
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}*/
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.activity_ble, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
Your help is much appreciated and please keep in mind that this is my first app and I'm still an amateur/beginner developer.
logcat:
08-06 16:21:39.152 5489-5489/nl.cargosys.iotcloudconnect E/AndroidRuntime: FATAL EXCEPTION: main
Process: nl.cargosys.iotcloudconnect, PID: 5489
java.lang.RuntimeException: Unable to pause activity {nl.cargosys.iotcloudconnect/nl.cargosys.iotcloudconnect.BleActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.stopScan(android.bluetooth.le.ScanCallback)' on a null object reference
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4179)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4145)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4119)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4093)
at android.app.ActivityThread.-wrap18(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.stopScan(android.bluetooth.le.ScanCallback)' on a null object reference
at nl.cargosys.iotcloudconnect.BleActivity.scanLeDevice(BleActivity.java:179)
at nl.cargosys.iotcloudconnect.BleActivity.onPause(BleActivity.java:121)
at android.app.Activity.performPause(Activity.java:7148)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1330)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4168)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4145) 
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4119) 
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4093) 
at android.app.ActivityThread.-wrap18(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
In your if condition below -
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())
The main problem lies in your -
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
// Set scan settings
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
// Set device filter (null is allowed)
filters = new ArrayList<ScanFilter>();
// START SCAN FOR BLE DEVICES!
scanLeDevice(true);
You check if the adapter is available and if not you start another activity for result, but you continue to do the operation in your scanner code and scan for device after your else. Ideally you should place the above code in your else statement and only start scanning device if you are 100% sure that you have Bluetooth enabled.
Update 1
Ok so this error is coming from your onPause() method where you are calling scanLeDevice(false); method. Now inside this method you do mLEScanner.stopScan(mScanCallback); but your mLEScanner is not yet initialized as the initialization code is in your else statement or after it in the line
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
So it is better if you do this in your method-
if(mLEScanner!=null)
{
mLEScanner.stopScan(mScanCallback);
}

Bluetooth disconnects when scanning barcode

I am using a Bluetooth printer and zxing barcode scanner for this project. My problem is that after I have the Bluetooth printer connected and I try to scan a barcode, using zxing, it disconnects the Bluetooth printer. Here is my code.
package com.zj.printdemo;
import com.zj.printdemo.R;
import android.app.Fragment;
import android.content.Intent;
import com.zj.btsdk.BluetoothService;
import com.zj.btsdk.PrintPic;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.view.View.OnClickListener;
import android.util.Log;
import android.view.ViewGroup;
public class PrintDemo extends Activity {
Button btnSearch;
Button btnSendDraw;
Button btnSend;
//Button btnClose;
Button clearBtn;
Button btnBarcode;
EditText edtContext;
EditText edtContextQTY;
EditText edtPrint;
private static final int REQUEST_ENABLE_BT = 2;
BluetoothService mService = null;
BluetoothDevice con_dev = null;
private static final int REQUEST_CONNECT_DEVICE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
//Button clearBtn = (Button)findViewById(R.id.btnClear);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//edtContext = (EditText) findViewById(R.id.txt_content);
mService = new BluetoothService(this, mHandler);
if( mService.isAvailable() == false ){
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
}
clearBtn = (Button)findViewById(R.id.btnClear);
OnClickListener ClearOnClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
edtContext.setText("");
edtContextQTY.setText("");
}
};
clearBtn.setOnClickListener(ClearOnClickListener);
btnBarcode = (Button) findViewById(R.id.btnBarcode);
OnClickListener BarcodeOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnBarcode) {
IntentIntegrator integrator = new IntentIntegrator(PrintDemo.this);
integrator.initiateScan();
}
}
};
btnBarcode.setOnClickListener(BarcodeOnClickListener);
}
public void onStart() {
super.onStart();
if( mService.isBTopen() == false)
{
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
try {
btnSendDraw = (Button) this.findViewById(R.id.btn_test);
btnSendDraw.setOnClickListener(new ClickEvent());
btnSearch = (Button) this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new ClickEvent());
btnSend = (Button) this.findViewById(R.id.btnSend);
btnSend.setOnClickListener(new ClickEvent());
//btnClose = (Button) this.findViewById(R.id.btnClose);
//btnClose.setOnClickListener(new ClickEvent());
edtContext = (EditText) findViewById(R.id.txt_content);
edtContextQTY = (EditText) findViewById(R.id.txt_contentQTY);
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
} catch (Exception ex) {
Log.e("������Ϣ",ex.getMessage());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mService != null)
mService.stop();
mService = null;
}
class ClickEvent implements View.OnClickListener {
public void onClick(View v) {
if (v == btnSearch) {
Intent serverIntent = new Intent(PrintDemo.this,DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
} else if (v == btnSend) {
String msg = edtContext.getText().toString();
String msgQTY = edtContextQTY.getText().toString();
if( msg.length() > 0 ){
mService.sendMessage("ItemID:"+msg+"\n","ItemQTY:"+msgQTY+"\n");
}
} //else if (v == btnClose) {
//mService.stop();}
else if (v == btnSendDraw) {
String msg = "";
String lang = getString(R.string.strLang);
//printImage();
byte[] cmd = new byte[3];
cmd[0] = 0x1b;
cmd[1] = 0x21;
if((lang.compareTo("en")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("Congratulations!\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " You have sucessfully created communications between your device and our bluetooth printer.\n\n"
+" the company is a high-tech enterprise which specializes" +
" in R&D,manufacturing,marketing of thermal printers and barcode scanners.\n\n";
mService.sendMessage(msg,"GBK");
}else if((lang.compareTo("ch")) == 0){
cmd[2] |= 0x10;
mService.write(cmd);
mService.sendMessage("��ϲ����\n", "GBK");
cmd[2] &= 0xEF;
mService.write(cmd);
msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n"
+ " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n";
mService.sendMessage(msg,"GBK");
}
}
}
}
/**
* Handler BluetoothService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connect successful",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(true);
btnSend.setEnabled(true);
btnSendDraw.setEnabled(true);
break;
case BluetoothService.STATE_CONNECTING:
Log.d("��������","��������.....");
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Log.d("StateNone","�ȴ�����.....");
break;
}
break;
case BluetoothService.MESSAGE_CONNECTION_LOST:
Toast.makeText(getApplicationContext(), "Device connection was lost",
Toast.LENGTH_SHORT).show();
//btnClose.setEnabled(false);
btnSend.setEnabled(false);
btnSendDraw.setEnabled(false);
break;
case BluetoothService.MESSAGE_UNABLE_CONNECT:
Toast.makeText(getApplicationContext(), "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
} else {
finish();
}
break;
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
con_dev = mService.getDevByMac(address);
mService.connect(con_dev);
}
break;
case IntentIntegrator.REQUEST_CODE:
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
//formatTxt.setText("FORMAT: " + scanFormat);
edtContext.setText(scanContent);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
break;
}
}
#SuppressLint("SdCardPath")
private void printImage() {
byte[] sendData = null;
PrintPic pg = new PrintPic();
pg.initCanvas(384);
pg.initPaint();
pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
sendData = pg.printDraw();
mService.write(sendData);
}
}
My goal is to connect the printer, scan a barcode, and print a tag with the ID and quantity. Manual entry works, the printer works, and the barcode scanning works. Its only when you use the barcode scanner after you connect the printer that it will disconnect the printer.

How to change the location of the emergence of AdMob interstitial to start the application

How to change the location of the emergence of AdMob interstitial to start the application
Admob interstitial appears when you click on the camera icon
This is contrary to the policies of Admob
I want to make it appear within the application a way that is contrary to the policies of Admob
This is what happens now
I want to make it in this way
This is my GameOverscreen code.
package com.package.name;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import picture.profile.logo.football.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class LauncherActivity extends Activity{
private static final int CAMERA_PIC_REQUEST = 2;
private static final int SELECT_PICTURE = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
public static int imageFrom = 0;
protected static Uri outputFileUri = null;
public static String selectedImagePath;
private Uri fileUri;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
ImageView btnstart,img_more,img_rate,img_camera;
private AdView mAdView;
private InterstitialAd mInterstitial;
TextView txtname;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnstart=(ImageView)findViewById(R.id.start);
img_camera=(ImageView)findViewById(R.id.img_camera);
img_more=(ImageView)findViewById(R.id.img_more);
img_rate=(ImageView)findViewById(R.id.img_rate);
txtname=(TextView)findViewById(R.id.txt_appname);
Typeface font = Typeface.createFromAsset(getAssets(), "molten.ttf");
txtname.setTypeface(font);
mAdView = (AdView) findViewById(R.id.adViewad);
mAdView.loadAd(new AdRequest.Builder().build());
mInterstitial = new InterstitialAd(LauncherActivity.this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_intertestial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
});
btnstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra("imagePath", selectedImagePath);
startActivityForResult(i, SELECT_PICTURE);
}
});
img_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
img_rate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String appName = getPackageName();//your application package name i.e play store application url
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ appName)));
}
}
});
img_more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(getString(R.string.play_more_apps))));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
int k=0;
if (selectedImage != null)
{
try
{
k = getFileSize(selectedImage);
}
catch (Exception exception)
{
Toast.makeText(LauncherActivity.this, "unsupported media file", Toast.LENGTH_SHORT).show();
return;
}
}
if (selectedImage != null && k != 0)
{
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
selectedImagePath = cursor.getString(columnIndex);
cursor.close();
Log.e("path", selectedImagePath);
startActivity(new Intent(this,ShapeSecondActivity.class).putExtra("imagePath", selectedImagePath));
}
else
{
Toast.makeText(LauncherActivity.this, "unsupported media file",Toast.LENGTH_SHORT).show();
}
}
if (requestCode == CAMERA_PIC_REQUEST) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
selectedImagePath=fileUri.getPath();
startActivity(new Intent(this,ShapeSecondActivity.class).putExtra("imagePath", selectedImagePath));
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
private int getFileSize(Uri uri)
{
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int i = cursor.getColumnIndex("_size");
cursor.close();
return i;
}
}
Thank You
Your interstitial ad is showing right after the app launches and it's against AdMob policy.
If I understand correctly, you want to show the interstitial when the user clicks the camera icon. Then, remove this from your onCreate():
mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
super.onAdLoaded();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
});
And change your img_camera click listener to this:
img_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_PIC_REQUEST);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
}
});

Android Arduino Bluetooth communication crash on starting

i have been trying to use bluetooth to comunicate between arduino and bluetooth
and there is no errors on build
tell me what is wrong
i had issues with IO Exception but it solved now ... maybe
the app just crashes when i try to run it on phone
help me i am not that good at java
package com.example.administrator.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import android.os.ParcelUuid;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn, offBtn ,listBtn ,findBtn;
private TextView text;
private Button UpBtn ,DownBtn ,LeftBtn ,RightBtn;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private OutputStream outputStream;
private InputStream inStream;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = myBluetoothAdapter.getBondedDevices();
if (myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
UpBtn.setEnabled(false);
DownBtn.setEnabled(false);
LeftBtn.setEnabled(false);
RightBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
if(bondedDevices.size() > 0 ){
BluetoothDevice[] devices = (BluetoothDevice[]) bondedDevices.toArray();
BluetoothDevice device = devices[0];
ParcelUuid[] uuids = device.getUuids();
try{
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
} catch (IOException e){
}
}
//Movement
UpBtn = (Button) findViewById(R.id.Upbutton);
DownBtn = (Button) findViewById(R.id.Downbutton);
LeftBtn = (Button) findViewById(R.id.Leftbutton);
RightBtn = (Button) findViewById(R.id.Rightbutton);
UpBtn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
try {
C(v, 8);
}
catch (IOException e ){
System.out.println("3 SEND FAILED");
}
}
});
DownBtn.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
try {
C(v, 2);
} catch (IOException e) {
System.out.println("2 SEND FAILED");
}
}
});
LeftBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
C(v, 4);
} catch (IOException e) {
System.out.println(" 4 SEND FAILED");
}
}
});
RightBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
C(v, 6);
} catch (IOException e) {
System.out.println(" 6 SEND FAILED");
}
}
}
);
//.........................
//..................
//Normal Code
text = (TextView) findViewById(R.id.textView);
//text.setText ( "" + myBluetoothAdapter.getName());
onBtn = (Button) findViewById(R.id.Onbutton);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) findViewById(R.id.Offbutton);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) findViewById(R.id.Listbutton);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) findViewById(R.id.Pairedbutton);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view) {
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view) {
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for (BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
} else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view) {
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
public void C (View View , float H) throws IOException{
if(H == 8){
outputStream.write("8".toString().getBytes());
}
if(H == 2){
outputStream.write("2".toString().getBytes());
}
if(H == 4){
outputStream.write("4".toString().getBytes());
}
if(H == 6){
outputStream.write("6".toString().getBytes());
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
and here is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.myapplication" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Solved it , it just was a permission error
just added the bluetooth_admin permission and it worked !!
thanks HaMiD Sani for pointing that out .
It's pretty tough to point out the root of your problem without a log but this is the example https://goo.gl/d7YD92 (by google) that I followed a few months ago to make a robust bluetooth communication between android and arduino. Worked like a charge after a couple of hours of playing with it. One place I would also look is your manifest to make sure that you got all the necessary permissions.

Categories