2013-02-13 45 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.)