1

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!

Nyfiken Gul
  • 654
  • 4
  • 20

2 Answers2

1

Maybe, you can try to implement AudioManager.OnAudioFocusChangeListener https://developer.android.com/reference/android/media/AudioManager.OnAudioFocusChangeListener.html

 @Override
    public void onAudioFocusChange(int i) {
            if (i <= 0 && i != -3) {
               // pause
            } else if (i > 0) {
               // resume
            }
        }
    }
kara4k
  • 407
  • 5
  • 11
1

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+

Rosenpin
  • 862
  • 2
  • 11
  • 40