Can't Cancel Async Task In Android
Solution 1:
Your problem is not that you can't cancel the AsyncTask
. You probably get NullPointerException
because your call to setContentView()
goes through before AsyncTask.cancel()
has been successful. A onProgressUpdate()
gets called, only to find that the layout is now changed and there is no View
with id=R.id.pdf_text1
!
From documentation on AsyncTask.
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)
Since onCancelled()
runs on the UI thread, and you are certain that no subsequent calls to onProgressUpdate()
will occure, it's is a great place to call setContentView()
.
Override onCancelled()
in you AsyncTask
privateclassnaredi_pdfextendsAsyncTask<Void, String, Void> {
protectedVoiddoInBackground( Void... ignoredParams ) { // YOUR CODE HERE}protectedvoidonPostExecute( Void array ) { // YOUR CODE HERE}protectedvoidonProgressUpdate(String... values) {// YOUR CODE HERE}// ADD THIS@OverrideprotectedvoidonCancelled() {
// Do not call super.onCancelled()!// Set the new layoutsetContentView(R.id.other_layout);
}
}
Change close_pdf1()
publicvoidclose_pdf1(View view) {
if(start_pdf!=null) {
Log.v("not null","not null");
start_pdf.cancel(true);
}
}
And you should have an AsyncTask
that automatically changes your layout when cancelled. Hopefully you should not encounter any NullPointerException
either. Haven't tried the code though :)
Edit
If you feel fancy, follow Rezooms advice on using return
.
for(int i = 0; i < 1; i++) {
if(isCancelled()) {
return null;
}
.
.
.
}
Solution 2:
The return
statement cancels the execution of the doInBackground method, not break
.
Solution 3:
isCancelled is a propietary method of AsyncTask class.
You should define a private boolean property on your extended class, do something like this
privateclassmyAsyncTaskextendsAsyncTask<Void, String, Void> {
privateboolean isTaskCancelled = false;
publicvoidcancelTask(){
isTaskCancelled = true;
}
privatebooleanisTaskCancelled(){
return isTaskCancelled;
}
protectedVoiddoInBackground( Void... ignoredParams ) {
//Do some stuffif (isTaskCancelled()){
return;
}
}
protectedvoidonPostExecute( Void array )
{
//Do something
}
protectedvoidonProgressUpdate(String... values)
{
//Do something
}
}
Post a Comment for "Can't Cancel Async Task In Android"