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?
You will get the global application
Context
inonReceive()
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 anyContext
you want to do this. Alarms are not linked to a specificContext
, they are only linked to a specific application.If
dbHelper
is indeedstatic
and initialized at instance creation (not inonCreate()
), 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 theActivity
has been correctly set up. You would be better off moving such static methods to a general utilities class, which is not anActivity
and only containsstatic
methods. This would look less suspicious.