Running a service in separate thread and waking it every 10 minutes?
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.
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
:
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.
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.
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(..)
.
实际上,我用Timer
完全相同的情况下,它适用于我。
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
here your todo;
}
}}, 60000, 60000);
链接地址: http://www.djcxy.com/p/38952.html
上一篇: ScheduledThreadPoolExecutor用于周期性任务(使用Retrofit),只发射一次,不再发生