出自:http://www.92coding.com/blog/index.php/archives/362.htmlphp
概述: AsyncTask是在Android SDK 1.5以後推出的一個方便編寫後臺線程與UI線程交互的輔助類。AsyncTask的內部實現是一個線程池,全部提交的異步任務都會在這個線程池中的工做線程內執行,當工做線程須要跟UI線程交互時,工做線程會經過向在UI線程建立的Handler傳遞消息的方式,調用相關的回調函數,從而實現UI界面的更新。
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 html
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) |
61 |
HttpClient httpClient = new DefaultHttpClient(); |
63 |
HttpGet httpGet = new HttpGet(params[ 0 ]); |
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.xmljava
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加入相關權限android
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: initial; color: rgb(1, 150, 227);">
AsyncTask的實現原理
在分析實現流程以前,咱們先了解一下AsyncTask有哪些成員變量。apache
1 |
private static final int CORE_POOL_SIZE = 5 ; |
2 |
private static final int MAXIMUM_POOL_SIZE = 128 ; |
3 |
private static final int KEEP_ALIVE = 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.javaapp
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(); |
35 |
throw new RuntimeException( "An error occured while executing " + "doInBackground()" , t); |
38 |
message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(AsyncTask. this , 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.javaide
1 |
public final AsyncTask<Params, Progress, Result> execute(Params... params) |
3 |
if (mStatus != Status.PENDING) |