星期六, 9月 10, 2011

AsyncTask(一)

Android應用程式學習筆記

AsyncTask(一)

上次學到thread,當有複雜的計算要處理時,或者必須花長時間處理的工作,我們會希望另外使用一個執行續來處理這些工作,這樣方式為異步處理,避免讓應用程式看起來好像沒有回應,影響到使用者對於應用程式的體驗。因此,學到worker thread的使用。那其實還有一種方式也可以實現異步處理,那就是AsyncTask,今天就來大略了解一下。

AsyncTask允許你在使用者介面上執行異步的工作。它在worker thread中執行比較壅塞的操作,然後在UI thread發布結果,無須自己處理執行續或者Handler。

如果要使用它,必需子類AsyncTask還有實現doInBackground()回乎方法;如果要更新使用者介面,實現onPostExecute()從doInBackground()中傳遞結果,在UI thread完成更新,所以可以安全地更新畫面。最後在UI thread透過呼叫execute()方法運行task。

以下舉例


public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }
    
    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}

現在UI是安全的且程式碼更加簡化,因為我們已經把應該在worker thread完成的工作部分與應該在UI thread完成的工作部分分開了。

沒有留言:

張貼留言