概述: AsyncTask是在Android SDK 1.5之后推出的一個方便編寫后台線程與UI線程交互的輔助類。AsyncTask的內部實現是一個線程池,所有提交的異步任務都會在這個線程池中的工作線程內執行,當工作線程需要跟UI線程交互時,工作線程會通過向在UI線程創建的Handler傳遞消息的方式,調用相關的回調函數,從而實現UI界面的更新。
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類型即可。
例子:從網絡上下載圖片,下載完成后在UI界面上顯示出來,並會模擬下載進度更新。
AsyncTaskActivity.java
1 package com.szy.demo; 2 3 import org.apache.http.HttpResponse; 4 import org.apache.http.client.HttpClient; 5 import org.apache.http.client.methods.HttpGet; 6 import org.apache.http.impl.client.DefaultHttpClient; 7 8 import android.app.Activity; 9 import android.graphics.Bitmap; 10 import android.graphics.BitmapFactory; 11 import android.os.AsyncTask; 12 import android.os.Bundle; 13 import android.view.View; 14 import android.view.View.OnClickListener; 15 import android.widget.Button; 16 import android.widget.ImageView; 17 import android.widget.ProgressBar; 18 import android.widget.Toast; 19 20 /** 21 *@author coolszy 22 *@date 2012-3-1 23 *@blog http://blog.92coding.com 24 */ 25 public class AsyncTaskActivity extends Activity 26 { 27 28 private ImageView mImageView; 29 private Button mBtnDownload; 30 private ProgressBar mProgressBar; 31 32 @Override 33 public void onCreate(Bundle savedInstanceState) 34 { 35 super.onCreate(savedInstanceState); 36 setContentView(R.layout.main); 37 38 mImageView = (ImageView) findViewById(R.id.imageView); 39 mBtnDownload = (Button) findViewById(R.id.btnDownload); 40 mProgressBar = (ProgressBar) findViewById(R.id.progressBar); 41 mBtnDownload.setOnClickListener(new OnClickListener() 42 { 43 @Override 44 public void onClick(View v) 45 { 46 GetImageTask task = new GetImageTask(); 47 task.execute("http://www.baidu.com/img/baidu_sylogo1.gif"); 48 } 49 }); 50 } 51 52 class GetImageTask extends AsyncTask<String, Integer, Bitmap> 53 { 54 /** 55 * 處理后台執行的任務,在后台線程執行 56 */ 57 @Override 58 protected Bitmap doInBackground(String... params) 59 { 60 publishProgress(0);// 將會調用onProgressUpdate(Integer... progress)方法 61 HttpClient httpClient = new DefaultHttpClient(); 62 publishProgress(30); 63 HttpGet httpGet = new HttpGet(params[0]);// 獲取csdn的logo 64 final Bitmap bitmap; 65 try 66 { 67 HttpResponse httpResponse = httpClient.execute(httpGet); 68 //獲取返回圖片 69 bitmap = BitmapFactory.decodeStream(httpResponse.getEntity().getContent()); 70 } catch (Exception e) 71 { 72 73 return null; 74 } 75 publishProgress(100); 76 return bitmap; 77 } 78 79 /** 80 * 在調用publishProgress之后被調用,在UI線程執行 81 */ 82 protected void onProgressUpdate(Integer... progress) 83 { 84 mProgressBar.setProgress(progress[0]);// 更新進度條的進度 85 } 86 87 /** 88 * 后台任務執行完之后被調用,在UI線程執行 89 */ 90 protected void onPostExecute(Bitmap result) 91 { 92 if (result != null) 93 { 94 Toast.makeText(AsyncTaskActivity.this, "成功獲取圖片", Toast.LENGTH_LONG).show(); 95 mImageView.setImageBitmap(result); 96 } else 97 { 98 Toast.makeText(AsyncTaskActivity.this, "獲取圖片失敗", Toast.LENGTH_LONG).show(); 99 } 100 } 101 102 /** 103 * 在 doInBackground(Params...)之前被調用,在UI線程執行 104 */ 105 protected void onPreExecute() 106 { 107 mImageView.setImageBitmap(null); 108 mProgressBar.setProgress(0);// 進度條復位 109 } 110 111 /** 112 * 在UI線程執行 113 */ 114 protected void onCancelled() 115 { 116 mProgressBar.setProgress(0);// 進度條復位 117 } 118 } 119 120 }
Activity布局文件main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ProgressBar android:id="@+id/progressBar" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal"></ProgressBar> <Button android:id="@+id/btnDownload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下載圖片"/> <ImageView android:id="@+id/imageView" android:layout_height="wrap_content" android:layout_width="wrap_content" /> </LinearLayout>
記得在AndroidManifest.xml加入相關權限
<uses-permission android:name="android.permission.INTERNET"/>
運行結果:
AsyncTask的實現原理
在分析實現流程之前,我們先了解一下AsyncTask有哪些成員變量
1 private static final int CORE_POOL_SIZE =5;//5個核心工作線程 2 private static final int MAXIMUM_POOL_SIZE = 128;//最多128個工作線程 3 private static final int KEEP_ALIVE = 1;//空閑線程的超時時間為1秒 4 private static final BlockingQueue<Runnable> sWorkQueue = 5 new LinkedBlockingQueue<Runnable>(10);//等待隊列 6 private static final ThreadPoolExecutorsExecutor = new 7 ThreadPoolExecutor(CORE_POOL_SIZE, 8 MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, 9 sWorkQueue,sThreadFactory);//線程池是靜態變量,所有的異步任務都會放到這個線程池的工作線程內執行。
當點擊“下載圖片”按鈕之后會新建一個GetImageTask對象:
GetImageTask task = new GetImageTask();
此時會調用父類AsyncTask的構造函數:
AsyncTask.java
1 public AsyncTask() 2 { 3 mWorker = new WorkerRunnable<Params, Result>() 4 { 5 public Result call() throws Exception 6 { 7 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 8 return doInBackground(mParams); 9 } 10 }; 11 12 mFuture = new FutureTask<Result>(mWorker) 13 { 14 @Override 15 protected void done() 16 { 17 Message message; 18 Result result = null; 19 try 20 { 21 result = get(); 22 } catch (InterruptedException e) 23 { 24 android.util.Log.w(LOG_TAG, e); 25 } catch (ExecutionException e) 26 { 27 throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); 28 } catch (CancellationException e) 29 { 30 message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null)); 31 message.sendToTarget();// 取消任務,發送MESSAGE_POST_CANCEL消息 32 return; 33 } catch (Throwable t) 34 { 35 throw new RuntimeException("An error occured while executing " + "doInBackground()", t); 36 } 37 38 message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(AsyncTask.this, result));// 完成任務,發送MESSAGE_POST_RESULT消息並傳遞result對象 39 message.sendToTarget(); 40 } 41 }; 42 }
WorkerRunnable類實現了callable接口的call()方法,該函數會調用我們在AsyncTask子類中實現的doInBackground(mParams)方法,由此可見,WorkerRunnable封裝了我們要執行的異步任務。FutureTask中的protected void done() {}方法實現了異步任務狀態改變后的操作。當異步任務被取消,會向UI線程傳遞MESSAGE_POST_CANCEL消息,當任務成功執行,會向UI線程傳遞MESSAGE_POST_RESULT消息,並把執行結果傳遞到UI線程。 由此可知,AsyncTask在構造的時候已經定義好要異步執行的方法doInBackground(mParams)和任務狀態變化后的操作(包括失敗和成功)。 當創建完GetImageTask對象后,執行
1 |
task.execute( "http://www.baidu.com/img/baidu_sylogo1.gif" ); |
此時會調用AsyncTask的execute(Params...params)方法 AsyncTask.java
1 public final AsyncTask<Params, Progress, Result> execute(Params... params) 2 { 3 if (mStatus != Status.PENDING) 4 { 5 switch (mStatus) 6 { 7 case RUNNING: 8 throw newIllegalStateException("Cannot execute task:" + " the taskis already running."); 9 case FINISHED: 10 throw newIllegalStateException("Cannot execute task:" + " the taskhas already been executed " + "(a task canbe executed only once)"); 11 } 12 } 13 mStatus = Status.RUNNING; 14 onPreExecute();// 運行在ui線程,在提交任務到線程池之前執行 15 mWorker.mParams = params; 16 sExecutor.execute(mFuture);// 提交任務到線程池 17 return this; 18 }
當任務正在執行或者已經完成,會拋出IllegalStateException,由此可知我們不能夠重復調用execute(Params...params)方法。在提交任務到線程池之前,調用了onPreExecute()方法。然后才執行sExecutor.execute(mFuture)是任務提交到線程池。
前面我們說到,當任務的狀態發生改變時(1、執行成功2、取消執行3、進度更新),工作線程會向UI線程的Handler傳遞消息,Handler要處理其他線程傳遞過來的消息。在AsyncTask中,InternalHandler是在UI線程上創建的,它接收來自工作線程的消息,實現代碼如下:
AsyncTask.java
1 private static class InternalHandler extends Handler 2 { 3 @SuppressWarnings({"unchecked","RawUseOfParameterizedType"}) 4 @Override 5 public voidhandleMessage(Message msg) { 6 AsyncTaskResult result =(AsyncTaskResult) msg.obj; 7 switch (msg.what) { 8 caseMESSAGE_POST_RESULT: 9 // There is onlyone result 10 result.mTask.finish(result.mData[0]);//執行任務成功 11 break; 12 caseMESSAGE_POST_PROGRESS: 13 result.mTask.onProgressUpdate(result.mData);//進度更新 14 break; 15 caseMESSAGE_POST_CANCEL: 16 result.mTask.onCancelled();//取消任務 17 break; 18 } 19 } 20 }
當接收到消息之后,AsyncTask會調用自身相應的回調方法。
總結:1、 AsyncTask的本質是一個靜態的線程池,AsyncTask派生出的子類可以實現不同的異步任務,這些任務都是提交到靜態的線程池中執行。 2、線程池中的工作線程執行doInBackground(mParams)方法執行異步任務 3、當任務狀態改變之后,工作線程會向UI線程發送消息,AsyncTask內部的InternalHandler響應這些消息,並調用相關的回調函數
使用AsyncTask異步更新UI界面及原理分析 | 若水工作室 http://www.92coding.com/blog/index.php/archives/362.html