Correct way to cancel an AsyncTask in Android

Author: | Posted in Quick Tips No comments

It is advisable to cancel an AsyncTask after it complete it’s execution or you have no need to keep continue it’s execution. That time you need a correct way to cancel an AsyncTask in Android. It may be a OnBackPress event of Activity or OnDestroyView of Fragment. Because AsyncTask works on background thread and if you not cancel it properly, it may cause to crash in application.

Below is the simple method to cancel an Asynctask in Android.

public static void clearAsyncTask(AsyncTask<?, ?, ?> asyncTask) {
if (asyncTask != null) {
if (!asyncTask.isCancelled()) {
asyncTask.cancel(true);
}
asyncTask = null;
}
}

you just need to pass your AsyncTask object in this method like

MyAsyncTask mytask = new MyAsyncTask();
mytask.execute();
...
// pass AsyncTask object in method to
// cancel it in correct way,
// once you complete use of it.
clearAsyncTask(mytask);

If you want to know more about AsyncTask and it’s working you may check my this quicktips post.

 

 

(Visited 850 times, 1 visits today)