Android - Best practice for a periodic service

2019-07-20 19:24发布

问题:

I want to implement a service which its job is to periodically fetch updates from Internet. I know there is couple of ways to accomplish this purpose. I will list 2 of them. Please tell me what is more efficient and in practice what way is more common. Thanks in advance

1.Implement an infinite while(true) loop inside a separate thread, and then run this thread in service's onStartCommand. pseudo code:

class Updater extends Service {
    ...
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){

                    // fetching update...

                    Thread.sleep(FOR_A_WHILE);
                }
            }
        }).start();
    }
    ...
}

2.Schedule AlarmManager to periodically trigger an IntentService which fetching update

回答1:

Implement an infinite while(true) loop inside a separate thread, and then run this thread in service's onStartCommand.

The better implementation of that pattern would be to use a ScheduledExecutorService.

Please tell me what is more efficient and in practice what way is more common

The two implementations are not the same thing, and so you are comparing apples and oranges.

Your first approach -- whether using Thread.sleep() or ScheduledExecutorService -- says "do something every N milliseconds while the process is running and the device is awake".

Your second approach says "do something every N milliseconds, regardless of the state of my process (and, optionally, even if the device falls asleep), until I tell you to stop".

Hence, you use the first approach if you only need to do the work while your process is running. You use the second approach in other circumstances.



回答2:

Both method are going to be fine. But i will rather use the second approach because in the first on your service might get forced to close by the system at some point (musty on low end device with low memory) and that moment might be where it was about restart the thread therefore you will miss that iupdate , yes it will be triggered back later when memory will be available (you have to make sure of that when you create your service) but im just saying at the end of the day it really depend whether is important for you not skip anything update