My App works with BLE devices and searches them in the following way (API 21+):
adapter.getBluetoothLeScanner().startScan(filters, scanSettings, this);
It works just perfect for most devices (f.e. Samsung) but returns null
on some LGE and HTC devices (with Android 6.0) and crashes:
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(java.util.List, android.bluetooth.le.ScanSettings, android.bluetooth.le.ScanCallback)' on a null object reference
The app is targeted to pre-marshmallow android so the premissions are (should be) granted.
I think you might call startScan just right after adapter.enable(). Because BluetoothAdapter.enable() is an asynchronous call, so you might get NullPointer exception, you can try to register broadcast receiver to receive BluetoothAdapter status, something like below.
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
break;
case BluetoothAdapter.STATE_TURNING_OFF:
break;
case BluetoothAdapter.STATE_ON:
//to check if BluetoothAdapter is enable by your code
if(enableFlag){
adapter.getBluetoothLeScanner().startScan(filters, scanSettings, callBack);
}
break;
case BluetoothAdapter.STATE_TURNING_ON:
break;
}
}
}
};
You would need to enable Bluetooth by doing this:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
I've noticed that if Bluetooth isn't enabled on the device, mBluetoothAdapter.getBluetoothLeScanner(); returns null. You can enable Bluetooth by running the above code, which generates an Activity to allow the user enable it, or the user can go to their settings and turn on Bluetooth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With