How to Completely Kill/Remove/Delete/Stop an Asynctask

How to completely kill/remove/delete/stop an AsyncTask

AsyncTask does not cancel process on

myAsynTask.cancel(true) 

For that you have to stop it manually.

for example you are downloading video in doInBackground(..) in while/for loop.

protected Long doInBackground(URL... urls) {

for (int i = 0; i < count; i++) {
// you need to break your loop on particular condition here

if(isCancelled())
break;
}
return totalSize;
}

how to kill an async task?

You can use task.cancel(true); but usually it works if you have a loop in your doInBackground() and check the value of isCancelled in it .But in your case there is not a loop.

how to terminate AsyncTask in Android?

There is no way to cancel the AsyncTask, even with cancel method.

You need to implement your logic for canceling the task manually, see this link :

How to completly kill/remove/delete/stop an AsyncTask in Android

Ideal way to cancel an executing AsyncTask

Just discovered that AlertDialogs's boolean cancel(...); I've been using everywhere actually does nothing. Great.

So...

public class MyTask extends AsyncTask<Void, Void, Void> {

private volatile boolean running = true;
private final ProgressDialog progressDialog;

public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);

progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});

}

@Override
protected void onPreExecute() {
progressDialog.show();
}

@Override
protected void onCancelled() {
running = false;
}

@Override
protected Void doInBackground(Void... params) {

while (running) {
// does the hard work
}
return null;
}

// ...

}

How to cancel AsyncTask when Activity finishes?

I don't understand if your "cancel" means rollback but you have a cancel method on the AsyncTask class.

Android: Cancel Async Task

FOUND THE SOLUTION:
I added an action listener before uploadingDialog.show() like this:

    uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
myTask.cancel(true);
//finish();
}
});

That way when I press the back button, the above OnCancelListener cancels both dialog and task. Also you can add finish() if you want to finish the whole activity on back pressed. Remember to declare your async task as a variable like this:

    MyAsyncTask myTask=null;

and execute your async task like this:

    myTask = new MyAsyncTask();
myTask.execute();


Related Topics



Leave a reply



Submit