Search code examples
androidbroadcastreceiverintentservice

BroadcastReceiver does not receive Broadcast from IntentService


I'm trying to send a broadcast from an IntentService to the activity that started it, this is how i register the Receiver in the activity:

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");
        }
    }
}

And this is how i send the broadcast from the IntentService:

if(D) Log.d(TAG, "Got here");
Intent testIntent = new Intent("test");
sendBroadcast(testIntent);
  • The service is created cause "Got here" gets logged,
  • the BroadcastReceiver is initialized before the service being created and
  • the activity is visible when the broadcast is sent.
  • the broadcast is not received, cause "Received broadcast..." is never logged

What could cause this problem?


Solution

  • You should register and unregister your receivers in onResume() and in onPause() respectively. Cause if you only register it in onCreate() and unregister in onPause(), then the next time the activity is brought to the foreground, onCreate() will not be called again and then it will not register the receiver again. But onResume() is always called on the activity being displayed.

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