2013-02-13 85 views
3

我对异步任务感到困惑。当我的活动重新启动时,我必须做些什么? 在我的活动中,onCreate()启动一个异步任务。 我知道,当android需要它时(即方向改变或其他),活动重新开始。 我没有这个问题...我认为重新启动一个新的异步任务是可以接受的。异步任务正在运行时重启活动

不过,我不知道我以前的异步任务发生了什么。 我有摧毁它吗?

我的第二个问题:如果我在之前的任务中有一个progressDialog会怎么样。我是否必须解除这个对话框(以及如何)?

+0

http://logc.at/2011/11/08/the-hidden-pitfalls-of-asynctask/ – baboo 2013-02-13 10:06:53

+0

您的第一个问题“当我的活动重新启动时,我必须做些什么?”您应该在onResume()方法内调用YourAsyncTask.execute()。如果您改变方向,我认为更好的解决方案是存储您的数据,而不是销毁您的AsyncTask并再次执行。 取消你的progressDialog只需调用YourAsyncTask.cancel(true); – Martin 2013-02-13 10:09:54

+0

进度对话框s * cks ...你应该避免em ... http://developer.android.com/guide/topics/ui/dialogs.html(搜索“避免ProgressDialog”) – Selvin 2013-02-13 10:37:18

回答

2

不,您的Asynctask将以您的活动以及您的progressDialog结束。当你的活动呼叫onRestart()它必须首先通过和onStop这将破坏你的活动,但不是你的应用程序。

欲了解更多有关活动 - http://developer.android.com/reference/android/app/Activity.html

此外,这将是更安全的取消Asynctask以及设置progressDialog为null。

Asynctask文档

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