停止在android中执行timertask的intent服务

时间:2012-03-31 07:29:18

标签: android android-intent intentservice

我正在使用意向服务定期向我的服务器发送查询以检查是否有任何更新。在目标服务中有一个计时器任务,它每3秒查询一次服务器,当应用程序关闭时,它开始运行 现在,当用户再次返回应用程序时,我想停止服务 我该怎么做?如何通过另一项活动来停止正在进行时间任务的意图服务? 请给出Intent Service的建议,因为这就是我正在使用的。

2 个答案:

答案 0 :(得分: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.
        }
       }
   };
}

只需bind进行服务(使用AUTO_CREATE_FLAG)并在需要时启动更新。 当您的活动显示刚刚再次绑定到服务并使其停止更新时。

答案 1 :(得分:0)

首先,IntentService无法停止。只有在完成队列中的所有任务后才会自行停止。因此,不应在此处使用IntentService。