How to force an IntentService to stop immediately with a cancel button from an Activity?

后端 未结 9 886
梦如初夏
梦如初夏 2020-11-30 00:10

I have an IntentService that is started from an Activity and I would like to be able to stop the service immediately from the activity with a \"cancel\" button in the activi

9条回答
  •  迷失自我
    2020-11-30 01:08

    As @budius already mentioned in his comment, you should set a boolean on the Service when you click that button:

    // your Activity.java
    public boolean onClick() {
       //...
       mService.performTasks = false;
       mService.stopSelf();
    }
    

    And in your Intent handling, before you do the important task of committing/sending the intent information, just use that boolean:

    // your Service.java
    public boolean performTasks = true;
    
    protected void onHandleIntent(Intent intent) {
       Bundle intentInfo = intent.getBundle();
       if (this.performTasks) {
          // Then handle the intent...
       }
    }
    

    Otherwise, the Service will do it's task of processing that Intent. That's how it was meant to be used, because I can't quite see how you could solve it otherwise if you look at the core code.

提交回复
热议问题