java如何在固定时间间隔后使用IntentService实现轮询?
我需要对服务器进行轮询,从服务器获取一些事件,并对事件执行操作。所有这些都必须在固定的时间间隔内异步完成
因此,我编写了一个扩展IntentService
的类,并在其onHandleIntent
方法中启动了线程
代码如下:-
MyService。java
public class MyService extends IntentService{
private String tag = "MyService";
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(tag, "onHandleIntent");
TestThread.startThread();
}
}
测试线程。java
public class TestThread {
private static Timer threadTimer = new Timer();
private static long pollingInterval = 5000;//in milliseconds
private static boolean pollingStarted = false;
public static void startThread() {
threadTimer.schedule(new TestTimer(), 0, pollingInterval);
pollingStarted= true;
}
private static class TestTimer extends TimerTask {
@Override
public void run() {
//get event lists
//do some work on the even list
}
}
}
在测试线程中。它从服务器获取一些事件列表,并根据事件执行任务
在安卓 website他们说
the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
因此,我的问题是,在上述实施中,投票会继续吗?如果不是,那么上述要求的正确实现方式是什么
# 1 楼答案
对于需要定期在服务中完成的后台任务,您应该使用AlarmManager以所需的时间间隔启动服务。工作完成后,服务将关闭,并随着警报再次启动。您还可以在服务中安排或禁用警报等等。。。。试着用谷歌搜索这个方向的答案
长时间运行的线程不是进行服务器轮询的安全或可靠的方法,尤其是在IntentService中。你永远不可能知道你的服务会发生什么,至少可以说,让一个线程保持活动状态并在后台服务中运行计时器并不是一个好的编程实践
为什么?例如:How do I keep the Thread of an IntentService alive?
因此,正确的方法是使用“常规的”服务+AlarmManager
Android Polling from a Server periodically
编辑:
******有一些答案说你不需要为定期任务提供服务:***
Running task periodicaly(once a day/once a week)
How to poll a webservice at finite interval from android?
你可以尝试在Alarm Manager onReceive方法中编写代码,但如果你打算在代码中做一些广泛的工作,我建议不要这样做,因为android doc说,广播onReceive方法应该用于更长的操作,而应该在其中启动一个服务,让它来完成这项工作
也可以看看这个http://developer.android.com/google/gcm/index.html&http://developer.android.com/google/gcm/index.html可能有用