Reputation: 135
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
Reputation: 213
In the code to handle click
1> is common used.
Upvotes: 0
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
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