Spectorsky
Spectorsky

Reputation: 667

How to pass context to BroadcastReceiver?

I need to pass activity context to onReceive of MyAlarmReceiver extends BroadcastReceiver class. For that, I pass the context while setting intent:

myAlarmManager.set(AlarmManager.RTC_WAKEUP, d.getTime(),   
    PendingIntent.getBroadcast(MainActivity.this, 1,
    myIntentAlarm, PendingIntent.FLAG_ONE_SHOT));

However, context in onReceive is not the same as one passed in myAlarmManager. Why?

Upvotes: 0

Views: 609

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006664

and there this context is used to create and show AlertDialog

Triggering a dialog based on an alarm is fairly dangerous to the user. You have no idea what the user is doing at that time, and the dialog may interfere with the user (e.g., you pop up a dialog over their real-time turn-by-turn navigation session). Please use a Notification, either all the time or based on a user preference.

Beyond that, you cannot rely on your original MainActivity instance to exist anymore at the time the alarm goes off. After all, it should be fairly obvious that if you schedule an alarm to occur a week from now, your original activity instance will have been long since destroyed.

You are welcome to post an event on an event bus (LocalBroadcastManager, greenrobot's EventBus, etc.). That way, if you do happen to have UI in the foreground, it can display the dialog. And, if you don't happen to have UI in the foreground, you can do something else (e.g., display a Notification). I have sample apps that show this for LocalBroadcastManager and for greenrobot's EventBus.

Upvotes: 0

Larry Schiefer
Larry Schiefer

Reputation: 15775

The Context provided to a BroadcastReceiver is not the same as what is used to create the BroadcastReceiver or anything you can modify. It is a limited variant of a Context and that is intentional by the framework. If you have anything significant to do in your BroadcastReceiver, you'll need to start your own Service or use some other mechanism to trigger it.

Upvotes: 1

Related Questions