Home » Android » Android AlarmManager in a Broadcastreceiver

Android AlarmManager in a Broadcastreceiver

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have braodcastreceiver, that broadcast receiver shall schedule an alarm.

Usually I would do

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
am.set(AlarmManager.RTC, time,  myPendingIntent); 

The problem is that getSystemService is not available in a Broadcast receiver only in an Activty. How would I do it here?

Thanks, A.

How to&Answers:

AndyAndroid,

getSystemService() is part of the Context. You will need to save the Context you receive in your onReceive() method like so…

private Context mContext;

@Override
public void onReceive(Context c, Intent i) {
    mContext = c;
}

Then..where you call getSystemService() you use…

AlarmManager am = (AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE);