Which context does BroadcastReceivers receive when listening for BOOT_COMPLETED?

527 views Asked by At

AlarmManagers in Android lose all of their registered alarms when phone loses power.

I use the following broadcast receiver to trigger at android bootup:

public class AlarmBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            Cursor alarmCursor = MainActivity.dbHelper.loadAlarms();
            // Iterate through every stored alarm and set those alarms.
            // ....
            alarmCursor.close();
        }
    }
}
  • When the broadcast receiver's onReceive is triggered at system bootup, what context parameter is given to the method? I have to know the context, because I need the context to cancel alarms set in that context.

  • I am assuming the call to MainActivity.dbHelper.loadAlarms() is not safe because MainActivity is not initialized in system bootup. Or is it safe because dbhelper and loadAlarms() are all initialized and declared static?

2

There are 2 answers

0
David Wasser On BEST ANSWER

When the broadcast receiver's onReceive is triggered at system bootup, what context parameter is given to the method? I have to know the context, because I need the context to cancel alarms set in that context.

You will get the global application Context in onReceive() in this case. However, it is irrelevant. You don't need to know.

To cancel the alarms later, you will create a PendingIntent and you can use any Context you want to do this. Alarms are not linked to a specific Context, they are only linked to a specific application.

I am assuming the call to MainActivity.dbHelper.loadAlarms() is not safe because MainActivity is not initialized in system bootup. Or is it safe because dbhelper and loadAlarms() are all initialized and declared static?

If dbHelper is indeed static and initialized at instance creation (not in onCreate()), then this call is fine. In general, calling static methods on activities is frowned upon, as it is easy to do something stupid assuming that the Activity has been correctly set up. You would be better off moving such static methods to a general utilities class, which is not an Activity and only contains static methods. This would look less suspicious.

3
Ankur Aggarwal On

It doesn't matter what type of Context your BroadcastReceiver receives (In any case, its ApplicationContext) because : 1) You should not use a DBHelper which is associated with an Activity. Instead, make it a Singleton and use it throughout your app. 2) Your AlarmManager should be set using a Service. So, its good idea to call the service in your onReceive() and set the Alarms from that service