2012年11月29日 星期四

[Android] AsyncTask


Java一般code都是在UI thread跑
除非另外開thread

而Android本身提供了Handler和AsyncTask來multithread,
讓developer將要跑比較久的部份放到背景去執行,
前端則可以無停滯地繼續做其他事情。

Handler的部份使用起來需要注意較多細節,在這邊先不介紹。

AsyncTask的使用template

public class SearchAsyncTask extends AsyncTask<String, Void, Boolean>{

        @Override

        protected void onProgressUpdate(Void... values) {

                super.onProgressUpdate(values);

        }



        @Override

        protected void onPreExecute() {

                super.onPreExecute();

        }



        protected Boolean doInBackground(String... strUrlFile) {

                // TODO

        }



        @Override

        protected void onPostExecute(Boolean result) {

                super.onPostExecute(result);

        }

}

當然,可以自行加上Constructor和其他Class。

AsyncTask的cycle

onPreExecute
→ (onProgressUpdate)
→ doInBackground
→ onPostExecute

onPreExecute(in UI thread)

做些要在UI thread設定好或者拿什麼參數的事情。

onProgressUpdate(in UI thread)

類似progressBar的效用,要用要從onPreExecute去啟動他,所以也是在UI thread跑,但可以在doInBackground內去做存取變更。

doInBackground(in another thread)

實際上要在另一個thread做的事情。

onPostExecute(in UI thread)

做完事情後的一些設定或notify變動之類的。

備註

第一行的String, Void, Boolean
分別代表
params, progress, result
也就分別代表
doInBackground, onProgressUpdate, onPostExecute的丟入或傳回參數
是可以自行變更的

Ex:
要丟String進doInBackground然後傳回Boolean
onPostExecute則接收由doInBackground傳回的Boolean

沒有留言:

張貼留言