Jesse
Jesse

Reputation: 2684

Android Exiting AsyncTask

I have an AsyncTask running a loop which only stops looping when exiting the app, a global "stop" boolean gets set and it stops the loop and finishes through the AsyncTask.

I have this code:

@Override
public void onBackPressed() 
{
     KillAllThreads(); 
}

@Override 
public void onUserLeaveHint() 
{     
    KillAllThreads();       
}

Now here is the thing. If I initiate the AsyncTask, onUserLeaveHint() gets called right away, and when the home button is pressed, it never fires this method. If I dont initiate the AsyncTask and let the activity load without doing anything, then when I press Home, it fires the onUserLeaveHint() method.

How am I supposed to stop the thread if the user clicks out of the app?

Upvotes: 1

Views: 1840

Answers (1)

Kenny
Kenny

Reputation: 5542

You should be able to call .cancel() on a AsyncTask, have you tried that?

Have a look at this sample project on my google docs, It illustrates the important aspects of AsyncTask:

  • starting a task, publishing progress, etc.
  • It shows how to cancel the running task.
  • It shows how to cancel a running task when your activity is paused or stopped.

link:

https://docs.google.com/leaf?id=0BwAnjRVwT4WzOWMwYjFhNTctOTUxYy00NjQwLTgwNWEtMmE5MzEyZWQ3NjUx&hl=en_US&authkey=CLnH8_ID

Upvotes: 2

Related Questions