Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Async task cancel/stop

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

I have tried

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

I also tried

asyncTaskObject.cancel(true);

This works specially when associated with an event.

But suppose the scenario is--- there are 4 AsyncTask. First call the second, second calls the third and third calls fourth. When the user enters the activity there is no dialogbox. Otherwise we could have used the onCancel method there. When user clicks on anywhere on the page the dialog box appears if user does not click anywhere then no dialog box is shown but async task keep running in the background.Suppose the user clicks the "back" button on or the navigational icon to the home page user.is taken out of the current activity. But the async task keep running in the background and eventually the app crashes. I have used to the cancel method in onBackPressed. But the problem is you cannot be sure which task is running and app carshes again.

What is the way out of this?

like image 763
D-D Avatar asked Nov 27 '12 13:11

D-D


People also ask

How to cancel Async task 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.

How to stop AsyncTask?

1. call Cancel() method of AsyncTask from where you want to stop the execution, may be based on the button click. asyncTask. cancel( true );

How to stop Async process in java?

Future<String> future = component. run(); future. cancel(true);

Why is async task being deprecated?

Official Reason for Deprecation of AsyncTask AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.


1 Answers

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();
}
like image 111
Abhishek Chauhan Avatar answered Oct 04 '22 03:10

Abhishek Chauhan