I'm, having trouble getting scan results back from the BLE scanner. I have the proper permissions (ACCESS_COARSE_LOCATION) in my AndroidManifest.xml as detailed below but get an exception that indicates I need the permissions that I have. Not surprisingly, the scanner call back is never invoked.
W/Binder: Caught a RuntimeException from the binder stub implementation.
java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results. I'm not sure why the exception is thrown but I certianly DON'T get scan call backs.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
ScanCallback btScanCallback = new ScanCallback()
{
@Override
public void onScanResult(int callbackType, final ScanResult result)
{
BluetoothDevice btDevice = result.getDevice();
Log.d(LOGTAG, "Found BLE device: " + btDevice.getName());
// Remove the device from the scanner select view if its there already
for( int i=0; i<btDeviceNameList.size(); i++)
{
String aDevice = btDeviceNameList.get(i);
if(aDevice.equalsIgnoreCase(btDevice.getName()))
{
btDeviceNameList.remove(i);
btDeviceList.remove(i);
break;
}
}
// Add the device to the scanner select view
btDeviceList.add(btDevice);
btDeviceNameList.add(btDevice.getName());
btListAdapter.notifyDataSetChanged();
}
@Override
public void onScanFailed(int errorCode)
{
Log.e(LOGTAG, "BT scan error: " + errorCode);
}
};
If you are using android 6.0 or greater than that. The app has to request location permission at running time. After getting Bluetooth Adapter, just insert one line of code as below to request location permission. When the app runs, a dialog will be showed to ask whether the users agree to shared their location.
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);