Search code examples
androidalarmmanageralarmresumepausing-execution

Pausing Service during alarm, resuming it afterwards


So I have a Service that I want to be able to listen for Alarms and temporarily shut itself down/pause whilst the alarm rings, and then resume itself afterwards. What my Service does is that it inflates a view using WindowManager on top of the screen - it's a lock screen app.. But as such, it's always on top of everything else..

This was easy enough to implement for incoming calls using a PhoneStateListener but I haven't seen anything as handy for alarms - I guess I could implement an AlarmManager.onAlarmListener that shuts my service down once the alarm rings, but I'm not sure of how I would turn it back on again afterwards.

Thankful for any help!


Solution

  • Finally figured it out!

    You can get the time of the next alarm like so:

      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
      alarmManager.getNextAlarmClock().getTriggerTime()
    

    So just add this to your service onCreate method:

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            if (alarmManager.getNextAlarmClock() != null) {
                UIHandler.postAtTime(new Runnable() {
                    @Override
                    public void run() {
                        stopSelf();
                    }
                }, alarmManager.getNextAlarmClock().getTriggerTime());
            }
    

    Essentially what it does is to get the time of your next alarm in milliseconds, then post a runnable at the time of the next alarm.

    I believe it will only work on API 21+