0

I have a BroadcastReceiver, and the onReceive is called from two different postExecute methods in two different asyncTasks, in two different Activities.

I have a third activity that is running all the time called HomeActivity, and I want to publish some text to the HomeActivity's UI from the onReceive method.

Is it possible? I know that the context parameter is the context of the activity who raised the onReceive, but I want to access the HomeActivity's UI.

Here is the code

public class MyBroadcastReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        // here I want to publish some text to the HomeActivity 
    }

}

any ideas? thanks in advance

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101

1 Answers1

1

You want to change text in your running activity based on what you receive in the onReceive of the BroadcastReceiver? Right? One way is that you can use LocalBroadcast. See LocalBroadcast Manager. For how to implement is, there is a great example on how to use LocalBroadcastManager?.

LocalBroadcast Manager is a helper to register for and send broadcasts of Intents to local objects within your process. The data you are broadcasting won't leave your app, so don't need to worry about leaking private data.`

Your HomeActivity can registers for this local broadcast. From the MyBroadcastReceiver you send a LocalBroadcast from within the onReceive (saying that hey, I received a message. Do you want to do something now activity). Then inside your Activity you can listen to the broadcast. This way if the activity is in the forefront/is active, it will receive the broadcast otherwise it won't. So, whenever you receive that local broadcast, you may change the text etc, if activity is open.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • thanks for your answer! lets say that I raise the onReceive from the postExecute in one of the other activities, (and in the onReceive I send the LocalBroadcast to the Home activity). one line code after I call LocalBroadcast, I finish the other activity, and only the HomeActivity is left, will I see the text i the HomeAtivity? does that count as activity being forefront/is active? thanks – Ofek Agmon Mar 11 '15 at 20:32
  • Till the time you are not killing HomeActivity, you should get the local broadcast... – Shobhit Puri Mar 11 '15 at 20:40