2012-10-15 60 views
1

報價從here得到的文檔的AsyncTask,它說的AsyncTask實例關閉UI線程

  • The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
  • The task instance must be created on the UI thread.
  • execute(Params...) must be invoked on the UI thread.
  • Do not call onPreExecute() , onPostExecute(Result) , doInBackground(Params...) , onProgressUpdate(Progress...) manually.

現在什麼是創建在UI線程的AsyncTask參考的原因是什麼?這是Looper的問題嗎?

回答

1

我認爲這將是毫無意義在其他地方創造的AsyncTask因爲的AsyncTask是專門用來做UI線程上的一些準備工作,然後做一些事情在另一個線程然後再張貼在UI線程任何結果。

2

我認爲這樣做是爲了確保Handler在UI線程上初始化,因此在處理程序的構造函數中,myLooper()將返回mainUIThreadLooper,稍後將發送的消息將轉入UI線程。

public abstract class AsyncTask<Params, Progress, Result> { 
    private static final InternalHandler sHandler = new InternalHandler(); 
.... 
} 

public Handler() { 
    ... 
    mLooper = Looper.myLooper(); 
    ... 
} 
0

請檢查this答案。

的AsyncTask.class必須在UI線程加載,因爲它有靜態田間引用處理程序:

private static final InternalHandler sHandler = new InternalHandler(); 

所以,如果你將與彎另一個線程運行AsynckTask的第一次( NonMainThred)然後任何實例上AsuncTask將發佈它的onPostExecute(及其他)方法,以特定NonMainThread沒有梅特在那裏你會試圖啓動您的AsyncTask從。

如果現在你試圖解決從onPostExecute任何Android的UI元素將出現以下錯誤崩潰:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.