Reputation: 1449
I have a service which has a countdown timer. After the end of the countdown timer, this service sends a broadcast message. I use the following code to send the message:
Intent intent = new Intent("CancelEvents");
intent.putExtra("message", "cancelled");
LocalBroadcastManager.getInstance(TimerClass.this).sendBroadcast(intent);
I have another activity which has a broadcast receiver. This is the code I use to receive the broadcast message:
@Override
protected void onCreate(Bundle savedInstanceState)
{
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(cancelReceiver,
new IntentFilter("CancelEvents"));
}
private BroadcastReceiver cancelReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String message = intent.getStringExtra("message");
if (message.equals("cancelled"))
{
Toast.makeText(this,
"Your Ride Got Cancelled", Toast.LENGTH_LONG).show();
}
}
};
The receiving works fine, but the problem is the message is received by all other activities too which don't have a receiver. How to stop this?
Upvotes: 1
Views: 273
Reputation: 3980
Move the Broadcast subscription code to a different part of your lifecycle.
@Override
protected void onStart()
{
super.onStart();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(cancelReceiver,
new IntentFilter("CancelEvents"));
}
and
@Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(cancelReceiver);
}
Explanation: Your Activity in in the background, but it is still subscribed, and is showing the Toast messages, not the other Activities.
Upvotes: 1
Reputation: 590
Unregister your broadcast by defining in onStop() callback of activity in which activity you have registered cancelReceiver in onCreate()...
@Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(cancelReceiver);
}
Upvotes: 1