Search code examples
androidbroadcastreceiver

How to assign action to broadcast receiver


My code is supposed to listen to callbacks which are made when a bluetooth headset pairs on unpairs.

 //The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver bReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            Toast.makeText(getBaseContext(), "paired", Toast.LENGTH_LONG).show();
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Toast.makeText(getBaseContext(), "unpaired", Toast.LENGTH_LONG).show();
        }
    }
};

The BluetoothDevice.ACTION_ACL_CONNECTED fires when bluetooth device is connected, but BluetoothDevice.ACTION_ACL_DISCONNECTED never shows any toast.

I am guessing this is because I haven't assigned the filters/actions properly in onCreate :

  IntentFilter BluetoothFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    registerReceiver(bReceiver, BluetoothFilter);

How do I add ACTION_ACL_DISCONNECTED in oncreate?


Solution

  • EDITED Add BluetoothFilter.addAction(ACTION_ACL_DISCONNECTED) before your registerReceiver.