我正在尝试从具有2个不同接收器的服务接收广播。一个接收器更新是一个视图,所以我在活动的onResume方法中注册它。
当应用程序不在前台时,我使用其他接收器,以便在后台服务完成时显示系统通知。
以下代码是我如何注册我的接收器:
@Override
protected void onPause() {
// unregister local
unregisterReceiver(localReceiver);
// register remote
registerReceiver(remoteReceiver, filter);
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
// remove remote receiver
// since remote is only registered in onPause it won't be registered during the first onResume call
// so we want to ignore any exceptions
try {
unregisterReceiver(remoteReceiver);
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "No receiver registered, could be first time");
}
// add local receiver
registerReceiver(localReceiver, filter);
Log.i(LOG_TAG, "resumed. should be registered");
}
这两个接收者在Activity类的顶部实例化如下:
BroadcastReceiver localReceiver = new BroadcastReceiver() { ... };
WaitTimeReceiver remoteReceiver = new WaitTimeReceiver();
服务将意图设为:
broadcastIntent = new Intent(Support.SERVICE_BR);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
// later on sends using
sendBroadcast(broadcastIntent);
活动中的过滤器匹配:
filter.addAction(Support.SERVICE_BR);
filter.addCategory(Intent.CATEGORY_DEFAULT);
以上所有工作暂停恢复功能都按预期工作,但我的问题是为什么LocalBroadcastManager不是?
使用LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this)
然后拨打lbm.registerReceiver(localReceiver)
并未收到我的任何广播。
为什么LocalBroadcastManager不接收我的任何广播?
答案 0 :(得分:3)
javascript:document.getElementsByClassName("arrow up login-required access-required").click();
注册的 BroadcastReceiver
只能接收与LocalBroadcastManager
一起发送的广播。 LocalBroadcastManager
接收方无法接收使用Activity
或Service
sendBroadcast()
方法发送的广播。
请改用LocalBroadcastManager
方法。例如:
LocalBroadcastManager#sendBroadcast()