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.