Ideal way to cancel an executing AsyncTask

前端 未结 9 2205
不思量自难忘°
不思量自难忘° 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条回答
  •  萌比男神i
    2020-11-22 06:41

    I don't like to force interrupt my async tasks with cancel(true) unnecessarily because they may have resources to be freed, such as closing sockets or file streams, writing data to the local database etc. On the other hand, I have faced situations in which the async task refuses to finish itself part of the time, for example sometimes when the main activity is being closed and I request the async task to finish from inside the activity's onPause() method. So it's not a matter of simply calling running = false. I have to go for a mixed solution: both call running = false, then giving the async task a few milliseconds to finish, and then call either cancel(false) or cancel(true).

    if (backgroundTask != null) {
        backgroundTask.requestTermination();
        try {
            Thread.sleep((int)(0.5 * 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (backgroundTask.getStatus() != AsyncTask.Status.FINISHED) {
            backgroundTask.cancel(false);
        }
        backgroundTask = null;
    }
    

    As a side result, after doInBackground() finishes, sometimes the onCancelled() method is called, and sometimes onPostExecute(). But at least the async task termination is guaranteed.

提交回复
热议问题