How do I pass data from a BroadcastReceiver through to an Activity being started?

Posted by Tom Hume on Stack Overflow See other posts from Stack Overflow or by Tom Hume
Published on 2010-04-11T11:36:15Z Indexed on 2010/04/11 11:43 UTC
Read the original article Hit count: 474

I've got an Android application which needs to be woken up sporadically throughout the day.

To do this, I'm using the AlarmManager to set up a PendingIntent and have this trigger a BroadcastReceiver. This BroadcastReceiver then starts an Activity to bring the UI to the foreground.

All of the above seems to work, in that the Activity launches itself correctly; but I'd like the BroadcastReceiver to notify the Activity that it was started by the alarm (as opposed to being started by the user). To do this I'm trying, from the onReceive() method of the BroadcastReceiver to set a variable in the extras bundle of the intent, thus:

    Intent i = new Intent(context, MyActivity.class);
    i.putExtra(wakeupKey, true);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);

In the onResume() method of my Activity, I then look for the existence of this boolean variable:

protected void onResume() {
    super.onResume();

    String wakeupKey = "blah";      
    if (getIntent()!=null && getIntent().getExtras()!=null)
        Log.d("app", "onResume at " + System.currentTimeMillis() + ":" + getIntent().getExtras().getBoolean(wakeupKey));
    else
        Log.d("app", "onResume at " + System.currentTimeMillis() + ": null");
}

The getIntent().getExtras() call in onResume() always returns null - I don't seem to be able to pass any extras through at all in this bundle.

If I use the same method to bind extras to the PendingIntent which triggers the BroadcastReceiver however, the extras come through just fine.

Can anyone tell me what's different about passing a bundle from a BroadcastReceiver to an Activity, as opposed to passing the bundle from an Activity to a BroadcastReceiver? I fear I may be doing something very very obvious wrong here...

© Stack Overflow or respective owner

Related posts about android

Related posts about intent