2013年6月1日 星期六

[Android] AsyncTask

AsyncTask from API 1.5+
不過事實上 1.0 and 1.1 上也有此功能 只是 API 為 UserTask

Lifecycle
  • activity 結束時 AsyncTask 會繼續執行直到完成,然後呼叫 onCancelled(Result result)或 onPostExecute(Result result),然而因為 activity 已不在,所以 AsyncTask 也無法做接下來的工作。
  • 所以希望能在 activity 結束前先取消 AsyncTask,因此呼叫 cancel(boolean mayInterruptIfRunning),mayInterruptIfRunning 表示是否中斷 執行 thread。


cancel() 不總能正確的發揮效用?!
  • cancel(false): 工作不會被中斷並完整執行完,但執行完後不會呼叫 onPostExecute()
  • cancel(true): 只是會試著盡早中斷我們的工作,若是遇到不可被中斷的工作(ex: BitmapFactory.decodeStream()) 就仍然會執行完。


Memory leaks
AsyncTask 會執有 activity reference。


Serial or parallel?? It depends on the API level.
假設執行下列兩個 task:

new AsyncTask1().execute();
new AsyncTask2().execute();

Before API 1.6 (Donut): Serial
等 task1 執行完才會再執行 task2。
=> performance problems.

API 1.6 to API 2.3 (Gingerbread): Parallel
同時執行在不同的 worker thread。
=> concurrency issues.

API 3.0 (Honeycomb) until now: Serial or parallel
public static void execute(AsyncTask as) {
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) {
        as.execute();
    } else {
        as.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}

* Reference - The dark side of AsyncTask

沒有留言:

張貼留言