Ideal way to cancel an executing AsyncTask

前端 未结 9 2111
不思量自难忘°
不思量自难忘° 2020-11-22 05:54

I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask. A Cancellable progress bar is sh

9条回答
  •  孤街浪徒
    2020-11-22 06:34

    If you're doing computations:

    • You have to check isCancelled() periodically.

    If you're doing a HTTP request:

    • Save the instance of your HttpGet or HttpPost somewhere (eg. a public field).
    • After calling cancel, call request.abort(). This will cause IOException be thrown inside your doInBackground.

    In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests method to that class and called this method directly after calling cancel.

提交回复
热议问题