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

后端 未结 9 885
梦如初夏
梦如初夏 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:01

    If using an IntentService, then I think you are stuck doing something like you describe, where the onHandleIntent() code has to poll for its "stop" signal.

    If your background task is potentially long-running, and if you need to be able to stop it, I think you are better off using a plain Service instead. At a high level, write your Service to:

    • Expose a "start" Intent to start an AsyncTask to perform your background work, saving off a reference to that newly-created AsyncTask.
    • Expose a "cancel" Intent to invoke AsyncTask.cancel(true), or have onDestroy() invoke AsyncTask.cancel(true).
    • The Activity can then either send the "cancel" Intent or just call stopService().

    In exchange for the ability to cancel the background work, the Service takes on the following responsibilities:

    • The AsyncTask doInBackground() will have to gracefully handle InterruptedException and/or periodically check for Thread.interrupted(), and return "early".
    • The Service will have to ensure that stopSelf() is called (maybe in AsyncTask onPostExecute/onCancelled).

提交回复
热议问题