0

I want to sent a message from a Fragment to an Activity (not the Fragment parent Activity, just another one).

Actually I do the same from a Service to the same Activity and it works great.

This is my code:

Fragment:

private void sendBroadcastMessage() {
    Intent intent = new Intent("my_event");
    // add data
    intent.putExtra("message", "test");
    LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}

Activity:

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Extract data included in the Intent
        String message = intent.getStringExtra("message");

    }
};

@Override
protected void onPause() {
    // Unregister since the activity is not visible 
    LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();    LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter("my_event"));
}

I've just followed that great post, but it only works from Service to Activity

I think it has something to do with the Context from the Fragment, maybe getActivity() is not the right way...

Any ideas? Thanks.

Community
  • 1
  • 1
Ale
  • 2,282
  • 5
  • 38
  • 67
  • 1
    Yeah, you can't really do that, because the other `Activity` isn't going to be active at the time of the broadcast. You'll have to use some other method to pass your data. – Mike M. May 19 '16 at 10:01
  • Thanks @MikeM. for your response. Ok but if the Activity is not active at the time of the broadcast, how does it work when the broadcast is sent from the Service? The Activity is not active either but it works...do you have any suggestion about how to implement that without the `LocalBroadcastManager `? – Ale May 19 '16 at 10:16
  • 1
    Uh, it shouldn't, unless we're not talking about the same thing, or unless they've updated the newest version of `LocalBroadcastManager` to offer its own version of sticky broadcasts. Anyhoo, you could use some form of persistent storage to keep the data until you start the other `Activity`, or keep it in your `Service` until the other `Activity` needs it, or use an event bus that offers sticky events, etc. – Mike M. May 19 '16 at 10:35
  • Alright I'm going to try one of your suggestions, thanks a lot you have helped me a lot ;) – Ale May 19 '16 at 11:26

1 Answers1

-1

Register broadcast in onCreate and unregister in onDestroy of your activity.

In your case it may be unregister in onPause. so unregister in onDestroy instead of onPause.

Thanks,

Bhuvnesh
  • 1,055
  • 9
  • 29