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;
}
// ...
}
Best way to cancel asynctask
What I have done in the past is set a synchronized boolean that the async task and its caller can see. When I want to cancel the async task I set the boolean to false (normally named active). Inside the async task, I check the flag at various points and if it is ever false (meaning it has been cancelled) then I just return without completing the rest of the task.
Without seeing your specific situation it is hard to be more specific.
Hope it helps,
Mike
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 - Cancel AsyncTask Forcefully
Just check isCancelled()
once in a while:
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
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()
Best way to cancel an HTTP downloader AsyncTask
I'd definitely go with HttpURLConnection
. And possibly would do something like:
- Add a public void cancel() method to my custom AsyncTask
implementation Implement
cancel()
aspublic void cancel() {
this.cancel(true);
mConnection.disconnect();
// TODO try close input stream
}From my activity call
mMyAsyncTask.cancel()
when required
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();
Cancel an AsyncTask Class in Android
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.)
For further details visit:
https://developer.android.com/reference/android/os/AsyncTask.html
Just like:
onPostExecute(Result result)
{
}
you can override a method for cancel to update your UI accordingly when your asyncTask is cancelled as follows:
onCancelled(Result result)
{
// here you can handle situation according to your requirements
}
So point of your interest here is that whenever you cancel your task before it enters into onPostExecute it will not go into onPostExecute but will jump to onCancelled. You can also call task.cancel(true); in postExecute according to your condition by applying required checks.
Related Topics
How to Have Multiple Styles Inside a Textview
Android: View.Setid(Int Id) Programmatically - How to Avoid Id Conflicts
How to Filter a Recyclerview With a Searchview
Fullscreen Activity in Android
How to Avoid Concurrency Problems When Using Sqlite on Android
Error in Launching Avd With Amd Processor
Exception 'Open Failed: Eacces (Permission Denied)' on Android
How to Determine When Fragment Becomes Visible in Viewpager
Get Filename and Path from Uri from Mediastore
Simple Android Recyclerview Example
Is There an Addheaderview Equivalent For Recyclerview
Why 'Pageradapter::Notifydatasetchanged' Is Not Updating the View
Firebase Offline Capabilities and Addlistenerforsinglevalueevent