Alarms operate outside the scope of your application, so you need to manually cancel them if you no longer need them. You can use the cancel() method of AlarmManager
to accomplish this.
Unfortunately I don't think there is an easy way to understand if your application is closing. On way could be using ActivityLifecycleCallbacks. Check this answer for more informations. As you can read there
Just check if the number of stopped activities is equal to the number
of started activities. If they're equal, your application is being
backgrounded
At this point you can set the alarm.
Conversely
If there are more started activities, your application is still
visible. If there are more resumed than paused activities, your
application is not only visible, but it's also in the foreground
when in this situation, you can use the cancel()
method of the AlarmManager
.
Bear in mind that all alarms are cancelled whenever the device is rebooted.