出自:http://www.92coding.com/blog/index.php/archives/362.html
概述: 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
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.xml
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: initial; color: rgb(1, 150, 227);">
AsyncTask的實現原理
在分析實現流程之前,我們先了解一下AsyncTask有哪些成員變量。
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.java
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.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; |
15 |
mWorker.mParams
= params; |
16 |
sExecutor.execute(mFuture); |
當任務正在執行或者已經完成,會拋出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 |
3 |
@SuppressWarnings ({ "unchecked" , "RawUseOfParameterizedType" }) |
5 |
public
voidhandleMessage(Message msg) { |
6 |
AsyncTaskResult
result =(AsyncTaskResult) msg.obj; |
8 |
caseMESSAGE_POST_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會調用自身相應的回調方法。
總結:1、 AsyncTask的本質是一個靜態的線程池,AsyncTask派生出的子類可以實現不同的異步任務,這些任務都是提交到靜態的線程池中執行。
2、線程池中的工作線程執行doInBackground(mParams)方法執行異步任務
3、當任務狀態改變之後,工作線程會向UI線程發送消息,AsyncTask內部的InternalHandler響應這些消息,並調用相關的回調函數
實例代碼下載地址:http://115.com/file/an99m34l#AsyncTaskDemo.rar