我有一个有倒数计时器的服务。在倒数计时器结束后,该服务发送广播消息。我使用以下代码发送消息:
Intent intent = new Intent("CancelEvents");
intent.putExtra("message", "cancelled");
LocalBroadcastManager.getInstance(TimerClass.this).sendBroadcast(intent);
我有另一个有广播接收器的活动。这是我用来接收广播消息的代码:
@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();
}
}
};
接收工作正常,但问题是所有其他活动收到的信息也没有接收者。如何阻止这个?
答案 0 :(得分:1)
将广播订阅代码移至生命周期的不同部分。
@Override
protected void onStart()
{
super.onStart();
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(cancelReceiver,
new IntentFilter("CancelEvents"));
}
和
@Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(cancelReceiver);
}
说明:您的活动在后台,但仍在订阅,并且正在显示Toast消息,而不是其他活动。