Search code examples
androidbroadcastreceiverintentfilterintentservice

Send a broadcast only to specific Activity


I have one Activity which creates a BroadcastReceiver with an IntentFilter in the method onCreate(...):

IntentFilter iFilter = new IntentFilter("action");

receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};

registerReceiver(receiver, iFilter);

On the other side is an IntentService, which shall send some data:

Intent intent = new Intent(getApplicationContext(), receiver.class);
intent.setAction("action");

[...]

sendBroadcast(intent);

But it seems not to work. No Broadcast ist received.
My service class is in an android lib, perhaps this makes trouble.

Thanks for any advices.


Solution

  • Just create the intent with your action.

    Intent intent = new Intent("action");
    [...]
    sendBroadcast(intent);
    

    And consider renaming "action" to something more meaningful, like "com.my.package.actions.SOME_ACTION".

    If you only want that your application components receive the broadcast then use:

    1. Register a permission in your Manifest with a signature protection level (and define a use-permission for that permission). More here.
    2. Use sendBroadcast(intent, permission), and specify the permission in 1.