Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Best practice for a periodic service

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

like image 531
frogatto Avatar asked Jan 29 '26 11:01

frogatto


1 Answers

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.

like image 54
CommonsWare Avatar answered Jan 31 '26 08:01

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!