Android筆記: AsyncTask 的使用

來源:互聯網
上載者:User

和使用匿名線程相比較來說 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) 此方法在主線程執行,任務執行的結果作為此方法的參數返回。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.