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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With