Cancel / Stop Async Task for Android

I want to know what is the best way to stop the async frm task.

I tried

@Override protected void onCancelled() { super.onCancelled(); mTask.cancel(true); } 

I also tried

 asyncTaskObject.cancel(true); 

This works specifically when associated with an event.

But suppose the script --- there are 4 AsyncTask. First call the second, second calls the third and third calls the fourth. When the user enters this operation, there is no dialog box. Otherwise, we could use the onCancel method. When the user clicks anywhere on the page, a dialog box appears if the user does not click anywhere and the dialog box does not appear, but the async task runs in the background. Assume that the user presses the back button or the navigation icon to its initial position, the user.is page is out of the current activity. But the async task continues to run in the background, and ultimately the application crashes. I used the cancel method in onBackPressed. But the problem is that you cannot be sure which task is running, and add the machines again.

What is the way out of this?

+8
android events android-asynctask
source share
3 answers

save the reference to the AsyncTask object as an instance variable, and then in onDestroy () do it

 @Override protected void onDestroy() { if (mTask != null) { mTask.cancel(true); } super.onDestroy(); } 
+12
source share

At http://developer.android.com/reference/android/os/AsyncTask.html there is a session called Threading Rules, which says that AsyncTasks instances should be created in the user interface thread, and execution should be triggered by the user interface thread. If you call execution from a user interface thread, you can cancel the thread that calls your TaskInstance.cancel (true);

+3
source share

I'm not quite sure when you want to cancel your tasks, but here are some tips: a) keep a link to each running task. b) add a rejection listener to your dialogue and cancel all tasks there (if that is what you want to do). c) cancel all tasks when the activity onStop callback is called (if this is what you want to do again).

0
source share

All Articles