Ejecute un servicio después de que el teléfono se haya desbloqueado durante un período de tiempo variable

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

AlarmManager does not require your "app being running all the time". In fact, it is specifically designed so that your app should not be "running all the time". -

When my app is force stopped by the user or the system, all alarms associated with my app no longer function. However, my app is ordinarily only stopped for at most a couple of seconds, so this generally isn't a problem. It is a problem for figuring out how long the phone has been in use however, as I cannot just keep a running process keeping track of the time elapsed, as this will be reset when my application is stopped for a short amount of time. -

"When my app is force stopped by the user or the system, all alarms associated with my app no longer function" -- and on Android 3.1+, your whole app will no longer work, until something runs one of your components manually (e.g., user launches one of your activities from the home screen). -

1 Respuestas

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 setRepeating method 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.

Respondido 04 ago 12, 05:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.