I’m looking for a method to run a service after a certain amount of time. However, I cannot use the standard AlarmManager for this problem as I don’t want to rely on my app being running all the time, and AlarmManager takes into account the time when the phone is locked.
Basically, the goal is for a service to run after the user has been using their phone for a set amount of time, such as one hour. This timer should allow for breaks in the time when the phone is locked or turned off.
After a bunch of research, I found that the best way to do this was the following:
setRepeatingmethod for an AlarmManager.When the service runs every 10 seconds, check if the phone is locked using the following code:
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);boolean locked = keyguardManager.inKeyguardRestrictedInputMode();
If the phone isn’t locked, then have the service increment a database variable that keeps track of time by 10 seconds.
Also have the service check after it updates the database whether or not the total unlocked time is more than the maximum time. If so, then activate whatever event.
If anyone comes up with a better (cleaner) method, I’ll accept that answer.