2012-03-31 19 views
2

我正在使用intent服務來定期發送查詢到我的服務器來檢查是否有任何更新。在意向服務中,有一個計時器任務,每3秒查詢一次服務器,當應用程序關閉時,它開始運行。
現在,當用戶再次回到應用程序時,我想停止服務。
我該怎麼做?一個正在進行時間任務的意圖服務如何停止形成另一個活動?
請給意向服務提供建議,因爲這是我正在使用的。停止意圖的服務,這是做android timertask在android

回答

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),並且您需要的時候開始更新。 當您的活動顯示再次綁定到服務並使其停止更新時。

0

首先,IntentService不能停止。它只有在它完成了隊列中的所有任務後纔會自行停止。因此,IntentService不應該在這裏使用。