16

I'm having a problem with sending a broadcast from a Service to an activity.

This is what I have in my Service class:

Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION);
sendBroadcast(intent);

I have many Activities and in one of my activities I have this:

   class MyBroadcast extends BroadcastReceiver {
            @Override
            public void onReceive(Context ctxt, Intent i) {


                System.out.println("received");

            }
        };

The problem I have is that my broadcast receiver doesn't receive anything!!

Help!

EDIT:

If I have many activities how can send a broadcast message to all of them. In other words can I apply the same broadcast receiver to all the activities !?

bytebiscuit
  • 3,446
  • 10
  • 33
  • 53

2 Answers2

3

You have to register the broadcast receiver before it can receive anything.

Have a look at this question.

Community
  • 1
  • 1
Flo
  • 27,355
  • 15
  • 87
  • 125
3

Like others said, you need to register the activity first to receive those broadcasts (see Flo's answer)

For your other quesition (re: EDIT). If you are taking the same action, you should create an overall Activity, and have your other activities extend that activity..

Then in this super class, implement the broadcast receiver registers on onResume and un register onStop..

Tolga E
  • 12,188
  • 15
  • 49
  • 61
  • onStart is the counterpart of onStop, so better to register in onStart and then unregister in onStop. – David Jun 24 '20 at 14:01