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
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:
AsyncTask.cancel(true)
, or have onDestroy() invoke AsyncTask.cancel(true)
.In exchange for the ability to cancel the background work, the Service takes on the following responsibilities:
doInBackground()
will have to gracefully handle InterruptedException and/or periodically check for Thread.interrupted(), and return "early".stopSelf()
is called (maybe in AsyncTask onPostExecute/onCancelled).