1

我正在尝试从 IntentService 向启动它的活动发送广播,这就是我在活动中注册接收器的方式:

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);
  • 创建该服务的原因是“到达这里”被记录,
  • BroadcastReceiver 在创建服务之前初始化,并且
  • 发送广播时,活动可见。
  • 未收到广播,因为从未记录过“已接收广播...”

什么可能导致这个问题?

4

1 回答 1

6

你应该registerunregister你的接收者分别在onResume()onPause()。因为如果你只在 中注册onCreate()和取消注册onPause(),那么下次将活动带到前台时,onCreate()将不会再次调用它,然后它不会再次注册接收器。但onResume()总是在显示的活动上调用。

public void onResume() {
    super.onResume();
    ....
    registerReceiver(myBroadcastReceiver, intentFilter);
}

public void onPause() {
    super.onPause();
    ...
    unregisterReceiver(myBroadcastReceiver);
}
于 2013-08-22T14:33:34.003 回答