Vignesh
Vignesh

Reputation: 2325

Is it possible to stop asynctask while doInBackground running?

I'm creating as async task in the ActivityB Oncreate(). In that task i'm running a infinite while loop in doInBackground() While i'm moving to previous acitivity and comes again to the activityB, another async task got created.

My Problem is now two infinite while loop is running. Is it possible to stop the async task when i move to previous activity?

Upvotes: 2

Views: 1433

Answers (2)

Anup Cowkur
Anup Cowkur

Reputation: 20553

There is a Cancel() method , but calling cancel(boolean mayInterruptIfRunning) doesn't necessarily stop the execution of the background process.

All that usually happens is that the AsyncTask will execute onCancelled(), and won't run onPostExecute() when it completes.

See the docs ('Canceling an async task' section)

http://developer.android.com/reference/android/os/AsyncTask.html

I'd review your app's design and re work it so that this condition does not arise rather than try to cancel running Async tasks.

Upvotes: 2

323go
323go

Reputation: 14274

Sure... check out isCancelled():

public Void doInBackground( .... ) {

   while( !isCancelled() ) {
       ...endless activity...
   }

   return null;
}

Upvotes: 3

Related Questions