use registerReceiver for non activity and non service class

I am trying to registerReceiver for BluetoothDevice events like ACTION_ACL_CONNECTED , ACTION_ACL_DISCONNECTED.

But the class in which I am using registerReceiver does not extend Activity class nor Service class – so I am passing Context to that class and registering receiver as follows

context.registerReceiver(ActionFoundReceiver, 
          new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

context.registerReceiver(ActionFoundReceiver, 
              new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

context.registerReceiver(ActionFoundReceiver, 
          new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));

and handling events as follows

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            // do some stuff
        }
    }
};

but when the device is connected or disconnected I am not able to trace is I mean the ActionFoundReceiver is not able to get called

Answer

I tried to solve it by using , but i really don’t know how safe is this and it is a good practice in this case or not.

if anyone has a better ans feel free to post

context.getApplicationContext().registerReceiver(ActionFoundReceiver, 
                  new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

Leave a Reply

Your email address will not be published. Required fields are marked *