I'm looking for a method to run a service after a certain amount of time. However, I cannot use the standard Administrador de alarmas 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.
preguntado el 31 de julio de 12 a las 14:07
After a bunch of research, I found that the best way to do this was the following:
- Create a service that is run every 10 seconds by the
setRepeatingmethod for an AlarmManager.
- If the app that creates the AlarmManager is ever stopped, once the app restarts, just restart the repeating alarm as well.
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.