Search code examples
androidandroid-servicealarmmanagerandroid-alarms

AlarmManager cannot work from a broadcast receiver


AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 

gives the ALARM_SERVICE cannot be resolved to a variable when called from a class that extends broadcastReceiver.

I tried the following,

AlarmManager alarmManager = (AlarmManager) getSystemService("alarm"); 

I get The method getSystemService(String) is undefined for the type MyReceiver


Solution

  • ALARM_SERVICE is a static constant inside Context. Refer to it like this:

    Context.ALARM_SERVICE
    

    Also, you need a context to call getSystemService, the onReceive() method should provide you with one.

    AlarmManager alarmManager = ctxt.getSystemService(Context.ALARM_SERVICE);