Search code examples
androidandroid-intentpermissionsbroadcastreceiver

How to register dynamic BroadcastReceiver with permissions?


I am trying to setup a dynamic broadcast receiver inside my service to receive broadcasts from another application. The twist is I want to require broadcaster to have specific permissions.

In AndroidManifest file of service application I created permission using normal protection leve. Application that will be broadcasting is using above mentioned permission. Broadcast is sent as following:

Intent intent = new Intent();
intent.setAction(Utils.ACTION_SEND_BUS_MESSAGE);
intent.putExtra(BusMessage.class.getSimpleName(), msg);
sendBroadcast(intent, Utils.PERMISSION_SEND_MESSAGE);

And in service receiver is register as:

registerReceiver(receiver, receiver.getIntentFilter(), Utils.PERMISSION_SEND_MESSAGE, null);

Unfortunately broadcasts to do not arrive to receiver. Removing permission from sendBroadcast and registerReceiver does allow broadcasts to be received.

I have also tested broadcaster to make sure that required permission is granted, which it is.


Solution

  • The twist is I want to require broadcaster to have specific permissions.

    However, you wrote more than that in your code.

    Broadcast is sent as following:

    In your code, you use sendBroadcast(intent, Utils.PERMISSION_SEND_MESSAGE). Quoting the documentation for that flavor of sendBroadcast() (with emphasis added):

    String naming a permission that a receiver must hold in order to receive your broadcast.

    Your sendBroadcast() requires the receiver to hold whatever Utils.PERMISSION_SEND_MESSAGE is, and apparently it does not.