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
private class naredi_pdf extends AsyncTask<Void, String, Void> {
protected Void doInBackground( Void... ignoredParams ) { // YOUR CODE HERE}
protected void onPostExecute( Void array ) { // YOUR CODE HERE}
protected void onProgressUpdate(String... values) {// YOUR CODE HERE}
// ADD THIS
@Override
protected void onCancelled() {
// Do not call super.onCancelled()!
// Set the new layout
setContentView(R.id.other_layout);
}
}
Change close_pdf1()
public void close_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
private class myAsyncTask extends AsyncTask<Void, String, Void> {
private boolean isTaskCancelled = false;
public void cancelTask(){
isTaskCancelled = true;
}
private boolean isTaskCancelled(){
return isTaskCancelled;
}
protected Void doInBackground( Void... ignoredParams ) {
//Do some stuff
if (isTaskCancelled()){
return;
}
}
protected void onPostExecute( Void array )
{
//Do something
}
protected void onProgressUpdate(String... values)
{
//Do something
}
}
Post a Comment for "Can't Cancel Async Task In Android"