Android異步處理二:使用AsyncTask異步更新UI界面

本博文地址:http://blog.csdn.net/mylzc/article/details/6772129,轉載請註明出處


Android異步處理系列文章索引

Android異步處理一:使用Thread+Handler實現非UI線程更新UI界面

Android異步處理二:使用AsyncTask異步更新UI界面

Android異步處理三:Handler+Looper+MessageQueue深入詳解

Android異步處理四:AsyncTask的實現原理


《Android異步處理一:使用Thread+Handler實現非UI線程更新UI界面》中,我們使用Thread+Handler的方式實現了異步更新UI界面,這一篇中,我們介紹一種更爲簡潔的實現方式:使用AsyncTask異步更新UI界面。

概述: AsyncTask是在Android SDK 1.5之後推出的一個方便編寫後臺線程與UI線程交互的輔助類。AsyncTask的內部實現是一個線程池,每個後臺任務會提交到線程池中的線程執行,然後使用Thread+Handler的方式調用回調函數(如需深入瞭解原理請看《Android異步處理四:AsyncTask的實現原理》)。

AsyncTask抽象出後臺線程運行的五個狀態,分別是:1、準備運行,2、正在後臺運行,3、進度更新,4、完成後臺任務,5、取消任務,對於這五個階段,AsyncTask提供了五個回調函數:

1、準備運行:onPreExecute(),該回調函數在任務被執行之後立即由UI線程調用。這個步驟通常用來建立任務,在用戶接口(UI)上顯示進度條。

2、正在後臺運行:doInBackground(Params...),該回調函數由後臺線程在onPreExecute()方法執行結束後立即調用。通常在這裏執行耗時的後臺計算。計算的結果必須由該函數返回,並被傳遞到onPostExecute()中。在該函數內也可以使用publishProgress(Progress...)來發佈一個或多個進度單位(unitsof progress)。這些值將會在onProgressUpdate(Progress...)中被髮布到UI線程。

3. 進度更新:onProgressUpdate(Progress...),該函數由UI線程在publishProgress(Progress...)方法調用完後被調用。一般用於動態地顯示一個進度條。

4. 完成後臺任務:onPostExecute(Result),當後臺計算結束後調用。後臺計算的結果會被作爲參數傳遞給這一函數。

5、取消任務:onCancelled (),在調用AsyncTask的cancel()方法時調用

 

AsyncTask的構造函數有三個模板參數:

1.Params,傳遞給後臺任務的參數類型。

2.Progress,後臺計算執行過程中,進步單位(progress units)的類型。(就是後臺程序已經執行了百分之幾了。)

3.Result, 後臺執行返回的結果的類型。

AsyncTask並不總是需要使用上面的全部3種類型。標識不使用的類型很簡單,只需要使用Void類型即可。

 

 

例子:《Android異步處理一:使用Thread+Handler實現非UI線程更新UI界面》實現的例子相同,我們在後臺下載CSDN的LOGO,下載完成後在UI界面上顯示出來,並會模擬下載進度更新。

例子工程文件下載

 AsyncTaskActivity.java


[java] view plaincopy

  1. package com.zhuozhuo;  

  2.   

  3.   

  4. import org.apache.http.HttpResponse;  

  5. import org.apache.http.client.HttpClient;  

  6. import org.apache.http.client.methods.HttpGet;  

  7. import org.apache.http.impl.client.DefaultHttpClient;  

  8.   

  9. import android.app.Activity;  

  10. import android.graphics.Bitmap;  

  11. import android.graphics.BitmapFactory;  

  12. import android.os.AsyncTask;  

  13. import android.os.Bundle;  

  14. import android.view.View;  

  15. import android.view.View.OnClickListener;  

  16. import android.widget.Button;  

  17. import android.widget.ImageView;  

  18. import android.widget.ProgressBar;  

  19. import android.widget.Toast;  

  20.   

  21. public class AsyncTaskActivity extends Activity {  

  22.       

  23.     private ImageView mImageView;  

  24.     private Button mButton;  

  25.     private ProgressBar mProgressBar;  

  26.       

  27.     @Override  

  28.     public void onCreate(Bundle savedInstanceState) {  

  29.         super.onCreate(savedInstanceState);  

  30.         setContentView(R.layout.main);  

  31.           

  32.         mImageView= (ImageView) findViewById(R.id.imageView);  

  33.         mButton = (Button) findViewById(R.id.button);  

  34.         mProgressBar = (ProgressBar) findViewById(R.id.progressBar);  

  35.         mButton.setOnClickListener(new OnClickListener() {  

  36.               

  37.             @Override  

  38.             public void onClick(View v) {  

  39.                 GetCSDNLogoTask task = new GetCSDNLogoTask();  

  40.                 task.execute("http://csdnimg.cn/www/images/csdnindex_logo.gif");  

  41.             }  

  42.         });  

  43.     }  

  44.       

  45.     class GetCSDNLogoTask extends AsyncTask<String,Integer,Bitmap> {//繼承AsyncTask  

  46.   

  47.         @Override  

  48.         protected Bitmap doInBackground(String... params) {//處理後臺執行的任務,在後臺線程執行  

  49.             publishProgress(0);//將會調用onProgressUpdate(Integer... progress)方法  

  50.             HttpClient hc = new DefaultHttpClient();  

  51.             publishProgress(30);  

  52.             HttpGet hg = new HttpGet(params[0]);//獲取csdn的logo  

  53.             final Bitmap bm;  

  54.             try {  

  55.                 HttpResponse hr = hc.execute(hg);  

  56.                 bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  

  57.             } catch (Exception e) {  

  58.                   

  59.                 return null;  

  60.             }  

  61.             publishProgress(100);  

  62.             //mImageView.setImageBitmap(result); 不能在後臺線程操作ui  

  63.             return bm;  

  64.         }  

  65.           

  66.         protected void onProgressUpdate(Integer... progress) {//在調用publishProgress之後被調用,在ui線程執行  

  67.             mProgressBar.setProgress(progress[0]);//更新進度條的進度  

  68.          }  

  69.   

  70.          protected void onPostExecute(Bitmap result) {//後臺任務執行完之後被調用,在ui線程執行  

  71.              if(result != null) {  

  72.                  Toast.makeText(AsyncTaskActivity.this"成功獲取圖片", Toast.LENGTH_LONG).show();  

  73.                  mImageView.setImageBitmap(result);  

  74.              }else {  

  75.                  Toast.makeText(AsyncTaskActivity.this"獲取圖片失敗", Toast.LENGTH_LONG).show();  

  76.              }  

  77.          }  

  78.            

  79.          protected void onPreExecute () {//在 doInBackground(Params...)之前被調用,在ui線程執行  

  80.              mImageView.setImageBitmap(null);  

  81.              mProgressBar.setProgress(0);//進度條復位  

  82.          }  

  83.            

  84.          protected void onCancelled () {//在ui線程執行  

  85.              mProgressBar.setProgress(0);//進度條復位  

  86.          }  

  87.           

  88.     }  

  89.       

  90.   

  91. }  




main.xml


[html] view plaincopy

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

  3.     android:orientation="vertical" android:layout_width="fill_parent"  

  4.     android:layout_height="fill_parent">  

  5.     <ProgressBar android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal"></ProgressBar>  

  6.     <Button android:id="@+id/button" android:text="下載圖片" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  

  7.     <ImageView android:id="@+id/imageView" android:layout_height="wrap_content"  

  8.         android:layout_width="wrap_content" />  

  9. </LinearLayout>  




manifest.xml


[html] view plaincopy

  1. <?xml version="1.0" encoding="utf-8"?>  

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  

  3.       package="com.zhuozhuo"  

  4.       android:versionCode="1"  

  5.       android:versionName="1.0">  

  6.     <uses-sdk android:minSdkVersion="10" />  

  7. <uses-permission android:name="android.permission.INTERNET"></uses-permission>  

  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  

  9.         <activity android:name=".AsyncTaskActivity"  

  10.                   android:label="@string/app_name">  

  11.             <intent-filter>  

  12.                 <action android:name="android.intent.action.MAIN" />  

  13.                 <category android:name="android.intent.category.LAUNCHER" />  

  14.             </intent-filter>  

  15.         </activity>  

  16.   

  17.     </application>  

  18. </manifest>  





運行結果:

 

流程說明:

1、  當點擊按鈕時,創建一個task,並且傳入CSDN的LOGO地址(String類型參數,因此AsyncTask的第一個模板參數爲String類型)

2、  UI線程執行onPreExecute(),把ImageView的圖片清空,progrssbar的進度清零。

3、  後臺線程執行doInBackground(),不可以在doInBackground()操作ui,調用publishProgress(0)更新進度,此時會調用onProgressUpdate(Integer...progress)更新進度條(進度用整形表示,因此AsyncTask的第二個模板參數是Integer)。函數最後返回result(例子中是返回Bitmap類型,因此AsyncTask的第個模板參數是Bitmap)。

4、  當後臺任務執行完成後,調用onPostExecute(Result),傳入的參數是doInBackground()中返回的對象。

 

總結:

AsyncTask爲我們抽象出一個後臺任務的五種狀態,對應了五個回調接口,我們只需要根據不同的需求實現這五個接口(doInBackground是必須要實現的),就能完成一些簡單的後臺任務。使用AsyncTask的方式使編寫後臺進程和UI進程交互的代碼變得更爲簡潔,使用起來更加方便,但是,AsyncTask也有一些缺憾,我們留到以後再講。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章