概述: AsyncTask是在Android SDK 1.5以後推出的一個方便編寫後臺線程與UI線程交互的輔助類。AsyncTask的內部實現是一個線程池,全部提交的異步任務都會在這個線程池中的工做線程內執行,當工做線程須要跟UI線程交互時,工做線程會經過向在UI線程建立的Handler傳遞消息的方式,調用相關的回調函數,從而實現UI界面的更新。java
AsyncTask抽象出後臺線程運行的五個狀態,分別是:一、準備運行,二、正在後臺運行,三、進度更新,四、完成後臺任務,五、取消任務,對於這五個階段,AsyncTask提供了五個回調函數:
一、準備運行:onPreExecute(),該回調函數在任務被執行以後當即由UI線程調用。這個步驟一般用來創建任務,在用戶接口(UI)上顯示進度條。
二、正在後臺運行:doInBackground(Params...),該回調函數由後臺線程在onPreExecute()方法執行結束後當即調用。一般在這裏執行耗時的後臺計算。計算的結果必須由該函數返回,並被傳遞到onPostExecute()中。在該函數內也能夠使用publishProgress(Progress...)來發佈一個或多個進度單位(unitsof progress)。這些值將會在onProgressUpdate(Progress...)中被髮布到UI線程。
3. 進度更新:onProgressUpdate(Progress...),該函數由UI線程在publishProgress(Progress...)方法調用完後被調用。通常用於動態地顯示一個進度條。
4. 完成後臺任務:onPostExecute(Result),當後臺計算結束後調用。後臺計算的結果會被做爲參數傳遞給這一函數。
五、取消任務:onCancelled (),在調用AsyncTask的cancel()方法時調用
AsyncTask的構造函數有三個模板參數:
1.Params,傳遞給後臺任務的參數類型。
2.Progress,後臺計算執行過程當中,進步單位(progress units)的類型。(就是後臺程序已經執行了百分之幾了。)
3.Result, 後臺執行返回的結果的類型。
AsyncTask並不老是須要使用上面的所有3種類型。標識不使用的類型很簡單,只須要使用Void類型便可。
例子:從網絡上下載圖片,下載完成後在UI界面上顯示出來,並會模擬下載進度更新。
AsyncTaskActivity.java android
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; |
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; |
25 |
public class AsyncTaskActivity extends Activity |
28 |
private ImageView mImageView; |
29 |
private Button mBtnDownload; |
30 |
private ProgressBar mProgressBar; |
33 |
public void onCreate(Bundle savedInstanceState) |
35 |
super .onCreate(savedInstanceState); |
36 |
setContentView(R.layout.main); |
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() |
44 |
public void onClick(View v) |
46 |
GetImageTask task = new GetImageTask(); |
52 |
class GetImageTask extends AsyncTask<String, Integer, Bitmap> |
58 |
protected Bitmap doInBackground(String... params) |
60 |
publishProgress( 0 ); // 將會調用onProgressUpdate(Integer... progress)方法 |
61 |
HttpClient httpClient = new DefaultHttpClient(); |
63 |
HttpGet httpGet = new HttpGet(params[ 0 ]); // 獲取csdn的logo |
67 |
HttpResponse httpResponse = httpClient.execute(httpGet); |
69 |
bitmap = BitmapFactory.decodeStream(httpResponse.getEntity().getContent()); |
80 |
* 在調用publishProgress以後被調用,在UI線程執行 |
82 |
protected void onProgressUpdate(Integer... progress) |
84 |
mProgressBar.setProgress(progress[ 0 ]); // 更新進度條的進度 |
88 |
* 後臺任務執行完以後被調用,在UI線程執行 |
90 |
protected void onPostExecute(Bitmap result) |
94 |
Toast.makeText(AsyncTaskActivity. this , "成功獲取圖片" , Toast.LENGTH_LONG).show(); |
95 |
mImageView.setImageBitmap(result); |
98 |
Toast.makeText(AsyncTaskActivity. this , "獲取圖片失敗" , Toast.LENGTH_LONG).show(); |
103 |
* 在 doInBackground(Params...)以前被調用,在UI線程執行 |
105 |
protected void onPreExecute() |
107 |
mImageView.setImageBitmap( null ); |
108 |
mProgressBar.setProgress( 0 ); // 進度條復位 |
114 |
protected void onCancelled() |
116 |
mProgressBar.setProgress( 0 ); // 進度條復位 |
Activity佈局文件main.xmlapache
1 |
<? xml version = "1.0" encoding = "utf-8" ?> |
3 |
android:orientation = "vertical" |
4 |
android:layout_width = "fill_parent" |
5 |
android:layout_height = "fill_parent" > |
7 |
android:id = "@+id/progressBar" |
8 |
android:layout_width = "fill_parent" |
9 |
android:layout_height = "wrap_content" |
10 |
style = "?android:attr/progressBarStyleHorizontal" ></ ProgressBar > |
12 |
android:id = "@+id/btnDownload" |
13 |
android:layout_width = "wrap_content" |
14 |
android:layout_height = "wrap_content" |
17 |
android:id = "@+id/imageView" |
18 |
android:layout_height = "wrap_content" |
19 |
android:layout_width = "wrap_content" /> |
記得在AndroidManifest.xml加入相關權限網絡
1 |
< uses-permission android:name = "android.permission.INTERNET" /> |
運行結果:
<a href="http://blog.92coding.com/wp-content/uploads/2012/03/AsyncTaskDemo.jpg" class="cboxElement" rel="example4" 362"="" style="text-decoration: none; color: rgb(1, 150, 227);">
AsyncTask的實現原理
在分析實現流程以前,咱們先了解一下AsyncTask有哪些成員變量。app
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對象:異步
1 |
GetImageTask task = new GetImageTask(); |
此時會調用父類AsyncTask的構造函數:
AsyncTask.javaide
3 |
mWorker = new WorkerRunnable<Params, Result>() |
5 |
public Result call() throws Exception |
7 |
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); |
8 |
return doInBackground(mParams); |
12 |
mFuture = new FutureTask<Result>(mWorker) |
22 |
} catch (InterruptedException e) |
24 |
android.util.Log.w(LOG_TAG, e); |
25 |
} catch (ExecutionException e) |
27 |
throw new RuntimeException( "An error occured while executing doInBackground()" , e.getCause()); |
28 |
} catch (CancellationException e) |
30 |
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, new AsyncTaskResult<Result>(AsyncTask. this , (Result[]) null )); |
31 |
message.sendToTarget(); // 取消任務,發送MESSAGE_POST_CANCEL消息 |
35 |
throw new RuntimeException( "An error occured while executing " + "doInBackground()" , t); |
38 |
message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(AsyncTask. this , result)); // 完成任務,發送MESSAGE_POST_RESULT消息並傳遞result對象 |
39 |
message.sendToTarget(); |
WorkerRunnable類實現了callable接口的call()方法,該函數會調用咱們在AsyncTask子類中實現的doInBackground(mParams)方法,因而可知,WorkerRunnable封裝了咱們要執行的異步任務。FutureTask中的protected void done() {}方法實現了異步任務狀態改變後的操做。當異步任務被取消,會向UI線程傳遞MESSAGE_POST_CANCEL消息,當任務成功執行,會向UI線程傳遞MESSAGE_POST_RESULT消息,並把執行結果傳遞到UI線程。
由此可知,AsyncTask在構造的時候已經定義好要異步執行的方法doInBackground(mParams)和任務狀態變化後的操做(包括失敗和成功)。
當建立完GetImageTask對象後,執行函數
此時會調用AsyncTask的execute(Params...params)方法
AsyncTask.java佈局
1 |
public final AsyncTask<Params, Progress, Result> execute(Params... params) |
3 |
if (mStatus != Status.PENDING) |
8 |
throw newIllegalStateException( "Cannot execute task:" + " the taskis already running." ); |
10 |
throw newIllegalStateException( "Cannot execute task:" + " the taskhas already been executed " + "(a task canbe executed only once)" ); |
13 |
mStatus = Status.RUNNING; |
14 |
onPreExecute(); // 運行在ui線程,在提交任務到線程池以前執行 |
15 |
mWorker.mParams = params; |
16 |
sExecutor.execute(mFuture); // 提交任務到線程池 |
當任務正在執行或者已經完成,會拋出IllegalStateException,由此可知咱們不可以重複調用execute(Params...params)方法。在提交任務到線程池以前,調用了onPreExecute()方法。而後才執行sExecutor.execute(mFuture)是任務提交到線程池。
前面咱們說到,當任務的狀態發生改變時(一、執行成功二、取消執行三、進度更新),工做線程會向UI線程的Handler傳遞消息,Handler要處理其餘線程傳遞過來的消息。在AsyncTask中,InternalHandler是在UI線程上建立的,它接收來自工做線程的消息,實現代碼以下:
AsyncTask.javaui
1 |
private static class InternalHandler extends Handler |
3 |
@SuppressWarnings ({ "unchecked" , "RawUseOfParameterizedType" }) |
5 |
public voidhandleMessage(Message msg) { |
6 |
AsyncTaskResult result =(AsyncTaskResult) msg.obj; |
8 |
caseMESSAGE_POST_RESULT: |
9 |
// There is onlyone result |
10 |
result.mTask.finish(result.mData[ 0 ]); //執行任務成功 |
12 |
caseMESSAGE_POST_PROGRESS: |
13 |
result.mTask.onProgressUpdate(result.mData); //進度更新 |
15 |
caseMESSAGE_POST_CANCEL: |
16 |
result.mTask.onCancelled(); //取消任務 |
當接收到消息以後,AsyncTask會調用自身相應的回調方法。
總結:一、 AsyncTask的本質是一個靜態的線程池,AsyncTask派生出的子類能夠實現不一樣的異步任務,這些任務都是提交到靜態的線程池中執行。
二、線程池中的工做線程執行doInBackground(mParams)方法執行異步任務
三、當任務狀態改變以後,工做線程會向UI線程發送消息,AsyncTask內部的InternalHandler響應這些消息,並調用相關的回調函數
實例代碼下載地址:http://115.com/file/an99m34l#AsyncTaskDemo.rar