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();
How to cancel or stop AsyncTask?
On your button click write the code
task.cancel(true);
where task
is the reference of the async task you have created and started
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;
}
// ...
}
Cancel AsyncTask after some time
You need a thread that cancels your task after a certain amount of time. That Thread could look like this:
public class TaskCanceler implements Runnable{
private AsyncTask task;
public TaskCanceler(AsyncTask task) {
this.task = task;
}
@Override
public void run() {
if (task.getStatus() == AsyncTask.Status.RUNNING )
task.cancel(true);
}
}
And when you call your AsyncTask, you need to run the cancle task after a certain amount of time (=the timeout, in this case 20 sec)
private Handler handler = new Handler();
private TaskCanceler taskCanceler;
...
LoadData task = new LoadData();
taskCanceler = new TaskCanceler(task);
handler.postDelayed(taskCanceler, 20*1000);
task.execute(...)
It's a good idea if you clean this up on cancel or finish with
if(taskCanceler != null && handler != null) {
handler.removeCallbacks(taskCanceler);
}
You can of course wrap this in an custom implementation of AsyncTask. I've used this pattern many times and it works like a charm. One thing to note, in rare cases the handler would not start, I suspect if you create it in the wrong context it will not survive in certain instances, so I forced the handler to be an the UI Thread with handler= new Handler(Looper.getMainLooper());
Android Async task cancel/stop
keep reference to AsyncTask object as instance variable and then in onDestroy() do this
@Override
protected void onDestroy() {
if (mTask != null) {
mTask.cancel(true);
}
super.onDestroy();
}
How to cancel AsyncTask and execute it again with new parameters?
You have to call the cancel
on the AsynTask
to cancel it.
It meant that control wont go in the onPostExecute(result)
if you have cancelled it when control is in doInBackGround(..)
and you have to check that your asynctask
has cancelled or not. You can do this isCancelled()
See here : http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)
See here : http://developer.android.com/reference/android/os/AsyncTask.html#isCancelled()
Related Topics
How to Get Current Time from Internet in Android
What Android Tools and Methods Work Best to Find Memory/Resource Leaks
Overriding the Home Button - How to Get Rid of the Choice
Android- Going Back to Previous Activity with Different Intent Value
How to Get an APK File from an Android Device
Show Compose Sms View in Android
Using Facebook Sdk in Android Studio
Soft Keyboard Open and Close Listener in an Activity in Android
How to Change the Background Color of Action Bar'S Option Menu in Android 4.2
How to Layout Text to Flow Around an Image
How to Read a Text File from the Sd Card in Android
Error Inflating Class Android.Support.Design.Widget.Navigationview
How to Get Onclick Event on Webview in Android
How to Get Resource Name from Resource Id
Single Textview with Multiple Colored Text
Android - Camera Preview Is Sideways
Android: Unable to Add Window. Permission Denied for This Window Type
How to Get the Width and Height of an Android.Widget.Imageview