My app will access a webservice to access data (even if the application is not in foreground), every 10 minutes. What is the best way to do that?
First do I need to start my service in seaparate thread? And how to make it get update from server every 10 minutes? Some people said handler.postdelayed and some using Alarm Manager. which one is better and do we have some examples.
Jeffrey Sharkey had an excellent presentation on the topic at Google IO 2009, watch closely from slide 21.
That should give you a good introduction to the best practices on the topic.
Excerpt: Don't use handlers or timers, go with AlarmManager and
setInexactRepeating(..)
.well actually I used
Timer
for exactly the same case and it works for me.If the updates will occur while your application is running, you can use a Timer, as suggested in other answers, or the newer
ScheduledThreadPoolExecutor
.If your application will update even when it is not running, you should go with the
AlarmManager
:Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.
You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.
Here is a sample using the latter: