Running a service in separate thread and waking it

2019-05-10 18:07发布

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.

4条回答
Lonely孤独者°
2楼-- · 2019-05-10 18:26

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(..).

查看更多
家丑人穷心不美
3楼-- · 2019-05-10 18:27

well actually I used Timer for exactly the same case and it works for me.

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }}, 60000, 60000);
查看更多
手持菜刀,她持情操
4楼-- · 2019-05-10 18:29

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.

查看更多
你好瞎i
5楼-- · 2019-05-10 18:42

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:

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call service
         }
      }, 0, 10, TimeUnit.MINUTES);
查看更多
登录 后发表回答