Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send broadcast from Service to Activity?

Tags:

android

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 !?

like image 670
bytebiscuit Avatar asked Nov 21 '11 12:11

bytebiscuit


People also ask

How send data from service to activity in Android?

So, in your activity, create your custom handler and pass it to your service. So, when you wants to put some data to your activity, you can put handler. sendMessage() in your Service (it will call handleMessage of your innerClass). Show activity on this post.

What method is used to send a broadcast event?

The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is called a Normal Broadcast. This is more efficient, but means that receivers cannot read results from other receivers, propagate data received from the broadcast, or abort the broadcast.

Does broadcast receiver work in background?

As an Android developer, you'll often run into the scenario where you need to perform tasks and display notifications for your app in the background. To retain battery power on our users device we are going to run background tasks using a broadcast receiver.


1 Answers

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..

like image 198
Tolga E Avatar answered Sep 30 '22 17:09

Tolga E