如何杀死一个Activity和AsyncTask [英] How to kill a Activity and the AsyncTask

查看:159
本文介绍了如何杀死一个Activity和AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小游戏.当我按下后退按钮时,activity将显示一个窗口取消游戏,是/否.

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

如果我按是",我将通过finish()返回到我的MainActivity.

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

我的问题是,我的Asynctask尚未完成,所以我无法再次开始游戏.我首先必须在最近使用的应用程序"中删除该应用程序.

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".

推荐答案

您需要实现两件事以停止AsyncTask的执行:

1.从要停止执行的位置调用AsyncTask的Cancel()方法.可能位于您的Activity的onStop()中,如下所示:
asyncTask.cancel(true);

2.现在,您必须使用doInBackground方法中的isCancelled方法来检查AsyncTask是否被取消.

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; 
}

为什么?由于以下来自AsyncTask的Android文档的描述:

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

取消任务
可以通过调用随时取消任务 取消(布尔).调用此方法将导致随后的调用 isCancelled()返回true.调用此方法后, onCancelled(Object),而不是onPostExecute(Object)将被调用 在doInBackground(Object [])返回之后.确保任务是 尽快取消,您应该经常检查退货 从doInBackground(Object [])定期获取isCancelled()的值,如果 可能(例如在循环内).

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.)

这篇关于如何杀死一个Activity和AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆