我正在使用意图服务定期向我的服务器发送查询以检查是否有任何更新。在意图服务中有一个定时器任务,它每 3 秒查询一次服务器,当应用程序关闭时它开始运行。
现在,当用户再次回到应用程序时,我想停止服务。
我该怎么做?如何从另一个活动中停止正在执行 timertask 的意图服务?
请为 Intent Service 提供建议,因为这就是我正在使用的。
问问题
496 次
2 回答
1
也许只使用服务而不是 IntentService 会更好。
public class UpdateService extends Service {
public class LocalBinder extends Binder {
public void startUpdates() {
// start updateThread if it not started, or
// notify about resuming probes
}
public void stopUpdates() {
// make updateThread to wait, until startUpdates
// called again.
//
// REMEMBER this method can be called when startUpdates didnt called.
}
}
// For simplicity we will use local binder.
private final IBinder binder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private Thread updateThread = new Thread() {
@Override
public void run() {
while (true) {
// Do updates. Sleep/awake managment.
}
}
};
}
只需绑定到服务(使用AUTO_CREATE_FLAG)并在需要时开始更新。当您的活动显示时,只需再次绑定到服务并使其停止更新。
于 2012-03-31T07:49:37.490 回答
0
首先,IntentService 无法停止。只有在完成队列中存在的所有任务后,它才会自行停止。因此,此处不应使用 IntentService。
于 2017-06-10T08:42:06.877 回答