我正在尝试从IntentService向发起它的活动发送广播,这就是我在活动中注册Receiver的方式:
private BroadcastReceiver mInitializer;
@Override
protected void onCreate(Bundle savedInstanceState) {
....
mInitializer = new InitializationReceiver();
IntentFilter initializer = new IntentFilter();
initializer.addAction(IntentConstants.Tasks.INITIALIZE);
initializer.addAction(IntentConstants.Initialization.INITIALIZE_IS_FIRST_START);
initializer.addAction("test");
registerReceiver(mInitializer, initializer);
....
}
private class InitializationReceiver extends BroadcastReceiver {
private InitializationReceiver() {
if(D) Log.d(TAG, "Instantiated InitializationReceiver");
}
@Override
public void onReceive(Context context, Intent intent) {
if(D) Log.d(TAG, "Received broadcast, intentAction: "+intent.getAction());
if(intent.getAction().equals(IntentConstants.Tasks.INITIALIZE)) {
if(D) Log.d(TAG, "Received Initialize Intent");
}
if(intent.getAction().equals(IntentConstants.Initialization.INITIALIZE_IS_FIRST_START)) {
if(D) Log.d(TAG, "Received First Start Intent");
}
}
}
这就是我从IntentService发送广播的方式:
if(D) Log.d(TAG, "Got here");
Intent testIntent = new Intent("test");
sendBroadcast(testIntent);
什么可能导致这个问题?
答案 0 :(得分:6)
您应该分别register
和unregister
中的onResume()
和onPause()
接收者。如果您只在onCreate()
中注册并在onPause()
中取消注册,则下次将活动带到前台时,onCreate()
将不再被调用,然后它将不会注册接收器再次。但是,onResume()
总是在显示的活动上调用。
public void onResume() {
super.onResume();
....
registerReceiver(myBroadcastReceiver, intentFilter);
}
public void onPause() {
super.onPause();
...
unregisterReceiver(myBroadcastReceiver);
}