我有一个要求,我需要对服务器进行轮询,从服务器获取一些事件并对事件执行操作。所有这些都必须异步并按固定时间间隔完成。
所以我编写了一个扩展 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
}
}
}
在TestThread.java中,它从服务器获取一些事件列表,并根据事件执行任务。
在 android 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.
所以我的问题是,轮询会在上述实现中继续吗?如果不是,那么上述要求的正确实现是什么。
最佳答案
对于需要定期在服务中完成的后台任务,您应该使用 AlarmManager 以所需的时间间隔启动您的服务。服务在工作完成后关闭,并再次启动并发出警报。您还可以在服务内安排或禁用闹钟等等……尝试用谷歌搜索该方向的答案。
长时间运行的线程不是进行服务器轮询的安全或可靠方式,尤其是在 IntentService 中。您永远无法知道您的服务会发生什么,至少可以说,让线程保持 Activity 状态并在带有计时器的后台服务中运行并不是一种好的编程习惯。
为什么?例如。 : How do I keep the Thread of an IntentService alive?
所以正确的方法是“常规”Service + 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?
它尝试你可以在你的警报管理器 onReceive 方法中执行你的代码,但如果你计划在你的代码中做一些广泛的工作,我会建议不要这样做,因为 android 文档说 BroadCasts onReceive 方法应该用于更长的操作,而你应该在那里启动服务并让它完成工作。
也可以看看这个 http://developer.android.com/google/gcm/index.html & http://developer.android.com/google/gcm/index.html它可能有用。
关于java - 如何在固定时间间隔后使用 IntentService 实现进行轮询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20740297/