Nick
Nick

Reputation: 135

How to kill a Activity and the AsyncTask

i am working on a little game. When I press the backbutton the activity will show a window cancel game yes/no.

If I press Yes i get via finish() back to my MainActivity.

My Problem is, that I can't start the game again, because my Asynctask wasn't finished. I first have to kill the app in the "recently used apps".

Upvotes: 0

Views: 650

Answers (5)

quocnhat7
quocnhat7

Reputation: 213

In the code to handle click

  • 1> Call finish(), and use AsyncTask.cancel() method on onStop() or onDestroy().
  • or 2> use AsyncTask.cancel(), and in AsyncTask.onCancelled() method, call finish() to end activity.

1> is common used.

Upvotes: 0

Richard Horc
Richard Horc

Reputation: 11

I would recommend using surface to code the actual game part instead of activity, that might help you get rip of this issue.

Upvotes: 1

AADProgramming
AADProgramming

Reputation: 6345

You need to implement two things to stop the AsyncTask execution:

1. call Cancel() method of AsyncTask from where you want to stop the execution. This could be in onStop() of your Activity , like below:
asyncTask.cancel(true);

2. Now you have to check whether the AsyncTask is cancelled or not by using isCancelled method inside the doInBackground method.

protected Object doInBackground(Object... x)  { 

   while (/* condition */)
   {
      ...
      if (isCancelled())  
         break;
   } 
   return null; 
}

Why? Because of below description from Android docs for AsyncTask:

Cancelling a task
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.)

Upvotes: 1

thestrongenough
thestrongenough

Reputation: 225

you can refer to this link for cancelling your async task

Upvotes: 1

StenSoft
StenSoft

Reputation: 9609

You need to cancel the AsyncTask in the Activity's onStop.

Upvotes: 2

Related Questions