我想实现一项服务,其工作是定期从 Internet 获取更新。我知道有几种方法可以实现这个目的。我将列出其中的 2 个。请告诉我什么更有效,在实践中什么方式更常见。提前致谢
1.在一个单独的线程中实现一个无限的 while(true) 循环,然后在服务的 onStartCommand
中运行这个线程。伪代码:
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.安排AlarmManager
定期触发一个IntentService
获取更新
最佳答案
Implement an infinite while(true) loop inside a separate thread, and then run this thread in service's onStartCommand.
该模式的更好实现是使用 ScheduledExecutorService
。
Please tell me what is more efficient and in practice what way is more common
这两个实现不是一回事,所以你是在比较苹果和橘子。
您的第一种方法 —— 无论是使用 Thread.sleep()
还是 ScheduledExecutorService
—— 表示“在进程运行期间每 N 毫秒做一些事情并且设备已唤醒”。
您的第二种方法是“每 N 毫秒执行一次操作,无论我的进程处于何种状态(并且,可选地,即使设备睡着了),直到我告诉您停止”。
因此,如果您只需要在进程运行时执行工作,则可以使用第一种方法。您在其他情况下使用第二种方法。
关于Android - 定期服务的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798659/