0

In Android, it is not possible to directly start a Bluetooth scan after you enabled Bluetooth on a device. If you would do this, you will get the following error:

D/BluetoothLeScanner: Scan failed, reason: app registration failed

The onScanFailed method will be called with error code 2 in the implemented ScanCallBack. Not much is known behind the reason of this error. But I found out the following (after a few hours of trying):

If you would wait ~5 seconds after you enabled Bluetooth and then start a scan (so not directly), it works. The scan starts with success. I came up with this temporary solution by the first answer of this question: Android BLE: "Scan failed, reason app registration failed for UUID"

As you can see that question is over a year old, however the questioner is using a separate Android library to handle BLE.

My question is, is there a better solution than the one I described above?

noname
  • 565
  • 6
  • 23
Displee
  • 670
  • 8
  • 20

1 Answers1

0

After enabling the Bluetooth adapter, it takes time for it to actually do all the initialization required, thus not allowing you to start scanning.

You can capture the broadcast event of the adapter's turn on event using the following broadcast receiver:

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);

            if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF) {
                if (state == BluetoothAdapter.STATE_TURNING_OFF) {
                    onBluetoothDisabling();
                } else {
                    onBluetoothDisabled();
                }
                requestEnableBluetooth();
            } else if (state == BluetoothAdapter.STATE_ON) {
                onBluetoothEnabled();
            }
        }
    }
};

Also, register the broadcast receiver in your onCreate() method:

IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

registerReceiver(mBroadcastReceiver, filter);
matdev
  • 4,115
  • 6
  • 35
  • 56
gkpln3
  • 1,317
  • 10
  • 24
  • That's correct. If you would now start a scan in your `onBluetoothEnabled` method, the scan will fail with the error I specified in my question. – Displee Dec 23 '19 at 15:34