BroadcastReceiver不从IntentService接收广播

时间:2013-08-22 14:10:41

标签: android broadcastreceiver intentservice

我正在尝试从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);
  • 创建服务导致“已在此处”被记录,
  • 在创建服务之前初始化BroadcastReceiver
  • 发送广播时活动可见。
  • 未收到广播,导致“已接收广播...”从未记录

什么可能导致这个问题?

1 个答案:

答案 0 :(得分:6)

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

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

public void onPause() {
    super.onPause();
    ...
    unregisterReceiver(myBroadcastReceiver);
}