10

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.

CSchulz
  • 10,882
  • 11
  • 60
  • 114

2 Answers2

10

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.
aromero
  • 25,681
  • 6
  • 57
  • 79
  • There are named more meaningful. ;) When I use that way everyone can receive my *Broadcast* and that I want to prevent. – CSchulz Jul 14 '11 at 18:29
  • That's the idea of a broadcast event. What do you mean by everyone? Your activities should stop listening somewhere in their lifecycle, probably in the onPause method. – aromero Jul 14 '11 at 18:54
  • I mean a *Broadcast* can received with different Activities not only my own, can't it? – CSchulz Jul 14 '11 at 19:02
  • Oh ok. Yes they can listen for your intents, but they would need to know the name of the action. – aromero Jul 14 '11 at 19:18
6

if the intent is inside your app only, consider using LocalBroadcastManager

android developer
  • 114,585
  • 152
  • 739
  • 1,270