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

My application works with BLE devices and searches for them as follows (API 21 +):

adapter.getBluetoothLeScanner().startScan(filters, scanSettings, this);

It works perfect for most devices (e.g. Samsung), but returns nullon some LGE and HTC devices (with Android 6.0) and a crash:

Java.lang.NullPointerException is called: tries to call the virtual method void android.bluetooth.le.BluetoothLeScanner.startScan (java.util.List, android.bluetooth.le.ScanSettings, android.bluetooth.le.ScanCallback) 'by the reference of the null object

The application is intended for pre-marshmallow android, so the tradition is provided (should be).

+4
source share
3

, startScan adapt.enable(). BluetoothAdapter.enable() , NullPointer, BluetoothAdapter, .

    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;
            }
        }
    }
};
+3

Bluetooth, :

if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }

, Bluetooth , mBluetoothAdapter.getBluetoothLeScanner(); null. Bluetooth, , Activity, , Bluetooth.

+2

Starting with Android 6.0, your application must have a new permission to access the BT adapter: Android 6.0 - Access to hardware identifier . And starting with Android 6.0, permissions must be requested at run time, and not during application installation: Android 6.0 - Request permissions at run time .

0
source

Source: https://habr.com/ru/post/1624969/


All Articles