Home » Android » Android bluetooth ACTION_DISCOVERY_FINISHED not working

Android bluetooth ACTION_DISCOVERY_FINISHED not working

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have written my first Android app and everything is working really well, except…in the routine, below, the ACTION_DISCOVERY_FINISHED never seems to get called (or broadcast or received or whatever). No matter what the block of code in that “else if” is not working.

I have only tested on my Motorola Atrix, so I am wondering if that is the issue. Since I am testing bluetooth functionality, I don’t think I can use the Android emulator for effective testing.

Thoughts?

private BluetoothAdapter mBtAdapter;
mBtAdapter.startDiscovery();

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        //do something
        }

        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            //do something else
        }
    }
}
How to&Answers:

2 possibles solutions:

  1. Instead of creating an annonymous receiver, subclass BroadcastReceiver with just the same implementation, then declare it in your project manifest (Remember to declare that your receiver receives these actions you want).

  2. Dynamically register it from your activity/service, this way:

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);
    

I’m not sure if you have to unregister it when registering it from an activity/service (I know you have to when registering from app’s context) so check it out.

Answer:

You need to add the line

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

to your manifest