I am running some tasks in UI part of my application.
While doing this lengthy task I need to show progress dialog so I am using AsysnTask to perform this.
When user pressed back button while progress bar going on , I need to cancel progress bar and I need to suspend that background work going on.
I am calling “dismiss()” on Progress Dialog so it’s dismissed.
I am calling “cancel(true)” on my AsysnTask object, I thought my backgroung operations got stopped , but still it is executing though I have called “cancel(true)”.
Then I have done some search on this issue and came to know that “cancel(true)” only called “onCancelled()” method of the AsyncTask.
I don’t know what I have to write in my onCancelled() method so that my background operations got stopped immediately.
My doInBackground() method something look like this:
protected void doInBackground()
{
Statement 1;
Statement 2;
Statement 3;
Statement 4;
Statement 5;
Statement 6;
Statement 6;
Statement 7;
Statement 8;
Statement 9;
}
let say in above code If got request to cancel after “Statement 4” then I don’t want to execute reaming statements.
The above “doInBackground()” is just a example to make it understandable , In actual my “doInbackground()” method will have 100’s of statements and I cant predict when I can get the request to cancel the operation.
Please help me how to do that.
In java threads are never terminated prematurely. You can kill a thread using native API, but Java API does not allow this anymore (even though there are some functions left that expose this interface, but they are not implemented and just throw exceptions).
Android exposes same philosophy, threads can not be terminated. You as developer is responsible for writing a thread in a such a way, so it reacts correctly when it is has been cancelled.
In your case you need to implement
doInBackground()so it checks whether thread has already been cancelled or not. For example:This is just an example, you can make a better implementation that checks thread state before executing next junk of its job.
By the way
isCancelled()was specifically designed for such use case. From documentation: