Luca Vitucci
Luca Vitucci

Reputation: 3734

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

What could cause this problem?

Upvotes: 1

Views: 2338

Answers (1)

Ritesh Gune
Ritesh Gune

Reputation: 16729

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

Upvotes: 6

Related Questions