2011-12-02 63 views
4

我有一個intentservice可以被用戶和我的應用程序自動調用。我需要能夠在用戶註銷應用程序時終止所有待處理的意圖,但似乎無法使其工作。我嘗試過stopService()和stopself(),但意圖在用戶註銷後繼續觸發intentservice。我會嘗試獲取intent的id,但這很困難,因爲每次intentservice開始時,持有intent id的變量都是空的。這裏是我的intentservice代碼:我該如何取消所有待處理意圖的服務

public class MainUploadIntentService extends IntentService { 
private final String TAG = "MAINUPLOADINTSER"; 
private GMLHandsetApplication app = null; 
private SimpleDateFormat sdf = null; 
public boolean recStops = true; 

public MainUploadIntentService() { 
    super("Main Upload Intent Service"); 

    GMLHandsetApplication.writeToLogs(TAG, 
      "GMLMainUploadIntentService Constructor"); 

} 

@Override 
protected void onHandleIntent(Intent intent) { 
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Started"); 
if (app == null) { 
    app = (GMLHandsetApplication) getApplication(); 
} 
uploadData(app); 
    GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Finished"); 
} 

@Override 
public void onDestroy() { 
GMLHandsetApplication.writeToLogs(TAG, "onDestroy Started"); 
app = null; 
    stopSelf(); 
    GMLHandsetApplication.writeToLogs(TAG, "onDestroy completed"); 
} 

public void uploadData(GMLHandsetApplication appl) { 
    //All of my code that needs to be ran 
} 
+0

看來,實際意圖闕並IntentService是不提供給Android開發者。 – user638049

回答

4

不幸的是,我不認爲這是可能實現,與標準IntentService方法,因爲它並沒有提供一種方式來中斷它,而它已經去。

有幾個選擇我可以想到,你可以嘗試看看它們是否適合你的需要。

  1. 複製IntentService代碼以對其進行自己的修改,使您可以刪除掛起的消息。看起來像有人在這裏取得了一些成功:Android: intentservice, how abort or skip a task in the handleintent queue
  2. 而不是複製所有的IntentService代碼,你可能也能夠綁定到它像一個普通的服務(因爲IntentService擴展服務),所以你可以編寫自己的函數刪除待處理消息。這個鏈接也被提及。
  3. 改爲將IntentService改爲常規服務。使用此選項,您可以更好地控制添加和刪除消息。

我聽起來像一個類似的情況,我使用IntentService,我最終只是將它轉換爲一個服務。這讓我可以同時運行這些任務,並且在我需要清除它們時也可以取消它們。

+0

我打算把這個標記爲固定的,因爲這是我能想到的最好的答案,即使我們決定採用一種更簡單的方法。謝謝 – user638049

0

只是一個想法,但你的onhandleintent裏面你可以有一個參數,檢查如果沒有運行的應用程序,那麼不運行代碼?例。在您的應用程序的開始,你可以有一個靜態無功

boolean appRunning; 

接下來在你的意圖的onhandle,當你設置appRunning爲false,將OnPause或活動的onDestroy後,你可以包裝在onhandleintent代碼一個布爾值:

protected void onHandleIntent(final Intent intent) { 
    if(MainActivity.appRunning){ 
     ... 
    } 
} 

只是一個想法