Handling Cancellation

You can handle cancellation of the background processing by overriding the onCancelled() method. The onCancelled() method runs on the UI thread and, if it's called, it means that the onPostExecute() method will not be called. Thus, any cleanup must be performed here. For this example, we perform the following operation:

@Override protected void onCancelled() {

Log.i(DEBUG_TAG, "onCancelled");


mProgressCounter = 0; QuizScoresActivity.this.


The onCancelled() method is called when the cancel() method of AsyncTask is called. This does not happen automatically. Instead, good practice is to cancel tasks when they are no longer needed. For the scores screen, you'll want to cancel the tasks if they're still running when the user leaves the screen for any reason. That is, you cancel them in the onPause() method of the Activity, as shown here: @Override protected void onPause() {

if (allScoresDownloader != null &&

allScoresDownloader.getStatus() != AsyncTask.Status.FINISHED) { allScoresDownloader.cancel(true);

if (friendScoresDownloader != null &&

friendScoresDownloader.getStatus() != AsyncTask.Status.FINISHED) { friendScoresDownloader.cancel(true);


0 0

Post a comment