You are intereset in asyncTask.cancel(true), actually passing true in its parameter, as in docs stay:
mayInterruptIfRunning true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete.
then inside your AsyncTask.doInBackground you can have try/catch as below - but that requires you to have blocking calls that throw InterruptedException, otherwise you need to check isCancelled() from time to time:
@Override
protected Void doInBackground(Void... params) {
try {
/// do work,
} catch (InterruptedException e) {
if ( isCancelled() ) {
// cancel(true) called, dont touch UI!
}
}
return null;
}
also, its safe to check for isCancelled() at the start of onPostExecute().
when it reaches to onPostExecute and wants to interact with UI, it crashes
thats other problem, if you interact inside AsyncTask with GUI, I suggest first: to make your AsyncTask a static class, pass reference to your Activity or Fragment to AsyncTask constructor and then store it as a WeakReference<MyActivity> actRef. Then when you need it use if ( actRef.get() != null ) { // use it. }. This way you want leak references to your activity/fragment or use dead UI object.