Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adapter.getBluetoothLeScanner() returns null on some Android 6.0 devices

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.

like image 290
4ntoine Avatar asked Jan 19 '16 13:01

4ntoine


2 Answers

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;
            }
        }
    }
};
like image 75
Charlie Wang Avatar answered Sep 21 '22 10:09

Charlie Wang


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.

like image 26
Tomi Avatar answered Sep 19 '22 10:09

Tomi