Android AlarmManager in a Broadcastreceiver

2019-04-24 09:23发布

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.

1条回答
\"骚年 ilove
2楼-- · 2019-04-24 09:53

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); 
查看更多
登录 后发表回答