I've an android service running, but I want to execute a specific service method every X hours to update data. What's the best aproach to do this without wasting android resources?
Asked
Active
Viewed 4,539 times
7
-
Why don't you just start the service once and then add a timer or make the thread sleep for the amount of time you like? – CodeKrieger Jun 21 '11 at 23:30
-
This would require that the service process executes *always*. For hours. This is not resource effective. – Peter Lillevold Jun 22 '11 at 08:17
-
Thanks! I'm learning, i'll search how to add timer. Any suggest? – Ferran Jun 22 '11 at 08:40
1 Answers
8
Look into the AlarmManager.
Clarification: since you want the service method to run with hourly intervals, you do not want to keep your service process running all this time. By using the AlarmManager
, the OS can kill the service when it is not needed, and then bring it up to execute the method when it is time.

Peter Lillevold
- 33,668
- 7
- 97
- 131
-
What if the intervals are a matter of minutes ? Is it a good idea to use the AlarmManager ? Or better make the thread called by the service sleep for few minutes ? – Leeeeeeelo Feb 11 '13 at 08:04
-
1@Leeeeeeelo - for efficiency, with small intervals (less than 10-15 minutes), you should not go with AlarmManager. There are discussions on that elsewhere on SO, e.g. http://stackoverflow.com/questions/11434056/how-to-run-a-method-every-x-seconds – Peter Lillevold Feb 11 '13 at 08:31