和使用匿名線程相比較來說 AsyncTask 有如下好處:
· 線程的開銷較大,如果每個任務都要建立一個線程,那麼應用程 序的效率要低很多;
· 線程無法管理,匿名線程建立並啟動後就不受程式的控制了,如果有很多個請求發送,那麼就會啟動非常多的線程,系統將不堪重負。
· 另外,前面已經看到,在新線程中更新UI還必須要引入handler,這讓代碼看上去非常臃腫。
AsyncTask定義了三種泛型型別 Params,Progress和Result。
· Params 啟動任務執行的輸入參數,比如HTTP請求的URL。
· Progress 背景工作執行的百分比。
· Result 後台執行任務最終返回的結果,比如String。
class LoadingTask extends AsyncTask<Void, Integer, Void>{//需要長時間阻塞處理的任務@Overrideprotected Void doInBackground(Void... params) {// 實現任務的執行工作// 線程中的處理,這兒不能操作UILog.i(TAG,"LoadingTask--doInBackground:");publishProgress(0);try {Thread.sleep(1000 * 5);//5秒後} catch (Exception e) {e.printStackTrace();}publishProgress(50);try {Thread.sleep(1000 * 5);} catch (InterruptedException e) {e.printStackTrace();}publishProgress(100);Log.i(TAG,"LoadingTask--doInBackground:"+params);return null;//publishProgress();//調用這個函數好後會啟用onProgressUpdate()事件 }@Overrideprotected void onCancelled() {Log.i(TAG,"LoadingTask--onCancelled:");super.onCancelled();}// 線程內更新處理@Overrideprotected void onProgressUpdate(Integer... values) {// 這邊用於處理線程未完成的提示處理,例如進度條更新pBar.setProgress(values[0]);Log.i(TAG,"LoadingTask--onProgressUpdate:");super.onProgressUpdate(values);}// 線程啟動初始化操作@Overrideprotected void onPreExecute() {// 任務啟動,比如顯示一個提示框或進度條Log.i(TAG,"LoadingTask--onPreExecute:");}// 阻塞任務執行完後的清理工作@Overrideprotected void onPostExecute(Void v) {// 線程處理結束,操作UI,關閉提示框或者關閉進度條pBar.setVisibility(View.INVISIBLE);Log.i(TAG,"LoadingTask--onPostExecute:");}}
· onPreExecute() 當任務執行之前開始調用此方法,可以在這裡顯示進度對話方塊。
· doInBackground(Params…) 此方法在後台線程執行,完成任務的主要工作,通常需要較長的時間。在執行過程中可以調用publicProgress(Progress…)來更新任務的進度。
· onProgressUpdate(Progress…) 此方法在主線程執行,用於顯示任務執行的進度。
· onPostExecute(Result) 此方法在主線程執行,任務執行的結果作為此方法的參數返回。