Android的 - 对于周期服务的最佳实践 [英] Android - Best practice for a periodic service
问题描述
我想实现一个服务,它的工作是定期获取从互联网更新。我知道有两种方法来实现这个目的。我将列出其中的2。请告诉我什么是更高效,更在实践中什么样的方式是比较常见的。在此先感谢
一个单独的线程里面 1.Implement一个无限的,而(真)循环,然后运行该线程服务的 onStartCommand
。伪code:
类更新扩展服务{
...
公众诠释onStartCommand(意向意图,诠释标志诠释startId){
新主题(新的Runnable接口(){
@覆盖
公共无效的run(){
而(真){ //获取更新... 视频下载(FOR_A_WHILE);
}
}
})。开始();
}
...
}
2.Schedule AlarmManager
定时触发一个 IntentService
其中获取更新
实现一个无限的,而一个单独的线程内(true)循环,然后运行该线程服务的onStartCommand。
块引用>更好地执行该模式将是使用
ScheduledExecutorService的
。
请告诉我什么是更高效,更在实践中什么样的方式是比较常见的。
块引用>这两种实现方式是不一样的东西,所以你比较苹果和桔子。
您第一种方法 - 无论是使用
视频下载()
或ScheduledExecutorService的
- 说做一些事情每n毫秒的而进程正在运行,该设备是醒着的。您第二种方法说做一些事情每隔N毫秒,无论我的过程中的状态(和可选,即使设备睡着了),直到我告诉你停止。
因此,您使用第一种方法,如果你只需要而你的进程正在运行,做的工作。您可以使用在其他情况下第二种方式。
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 anIntentService
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()
orScheduledExecutorService
-- 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.
这篇关于Android的 - 对于周期服务的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!