AsyncTask的本质是一个线程池,所有提交的异步任务都会在这个线程池中的工作线程内执行,当工作线程需要跟UI线程交互时,工作线程会通过向在UI线程创建的Handler传递消息的方式(Android使用Thread+Handler实现非UI线程更新界面),调用相关的回调函数,从而实现UI界面的更新。
AsyncTask和Handler的优缺点比较:http://blog.csdn.net/onlyonecoder/article/details/8484200
Activity
- package com.lmw.android.test;
-
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
-
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
- import android.widget.Toast;
-
- public class AsyncTaskActivity extends Activity {
-
- private ImageView mImageView;
- private Button mButton;
- private ProgressBar mProgressBar;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.asynctask);
-
- mImageView= (ImageView) findViewById(R.id.asynctask_imageView);
- mButton = (Button) findViewById(R.id.asynctask_download_btn);
- mProgressBar = (ProgressBar) findViewById(R.id.asynctask_progressBar);
- mButton.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- Task task = new Task();
- task.execute("http://pic7.nipic.com/20100517/4945412_113951650422_2.jpg");
- }
- });
- }
-
- class Task extends AsyncTask<String,Integer,Bitmap> {
-
- @Override
- protected Bitmap doInBackground(String... params) {
- publishProgress(0);
- HttpClient hc = new DefaultHttpClient();
- publishProgress(30);
- HttpGet hg = new HttpGet(params[0]);
- final Bitmap bm;
- try {
- HttpResponse hr = hc.execute(hg);
- bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
- } catch (Exception e) {
-
- return null;
- }
- publishProgress(100);
-
- return bm;
- }
-
- protected void onProgressUpdate(Integer... progress) {
- mProgressBar.setProgress(progress[0]);
- }
-
- protected void onPostExecute(Bitmap result) {
- if(result != null) {
- Toast.makeText(AsyncTaskActivity.this, "成功获取图片", Toast.LENGTH_LONG).show();
- mImageView.setImageBitmap(result);
- }else {
- Toast.makeText(AsyncTaskActivity.this, "获取图片失败", Toast.LENGTH_LONG).show();
- }
- }
-
- protected void onPreExecute () {
- mImageView.setImageBitmap(null);
- mProgressBar.setProgress(0);
- }
-
- protected void onCancelled () {
- mProgressBar.setProgress(0);
- }
-
- }
-
-
- }
asynctask.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <ProgressBar
- android:id="@+id/asynctask_progressBar"
- style="?android:attr/progressBarStyleHorizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
- </ProgressBar>
-
- <Button
- android:id="@+id/asynctask_download_btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="下载图片" >
- </Button>
-
- <ImageView
- android:id="@+id/asynctask_imageView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- </LinearLayout>
运行结果:
以上代码已经成功实现AsyncTask下载图片,以下是AsyncTask内部工作原理和流程分析:
在分析实现流程之前,先了解一下AsyncTask的成员变量。
- private static final int CORE_POOL_SIZE =5;
- private static final int MAXIMUM_POOL_SIZE = 128;
- private static final int KEEP_ALIVE = 1;
-
- private static final BlockingQueue<Runnable> sWorkQueue =
- new LinkedBlockingQueue<Runnable>(10);
-
- private static final ThreadPoolExecutorsExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
- MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue,sThreadFactory);
点击按钮之后会新建一个Task对象:
这时候会调用父类AsyncTask的构造函数:
AsyncTask.java
- public AsyncTask() {
- mWorker = new WorkerRunnable<Params, Result>() {
- public Result call() throws Exception {
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- return doInBackground(mParams);
- }
- };
-
- mFuture = new FutureTask<Result>(mWorker) {
- @Override
- protected void done() {
- Message message;
- Result result = null;
-
- try {
- result = get();
- } catch (InterruptedException e) {
- android.util.Log.w(LOG_TAG, e);
- } catch (ExecutionException e) {
- throw new RuntimeException("An error occured while executing doInBackground()",
- e.getCause());
- } catch (CancellationException e) {
- message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
- new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
- message.sendToTarget();
- return;
- } catch (Throwable t) {
- throw new RuntimeException("An error occured while executing "
- + "doInBackground()", t);
- }
-
- message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
- new AsyncTaskResult<Result>(AsyncTask.this, result));
- 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)和任务状态变化后的操作(包括失败和成功)。
当创建完Task对象后,执行
- task.execute("http://pic7.nipic.com/20100517/4945412_113951650422_2.jpg");
此时会调用AsyncTask的execute(Params...params)方法
AsyncTask.java
- public final AsyncTask<Params,Progress, Result> execute(Params... params) {
- if (mStatus != Status.PENDING) {
- switch (mStatus) {
- case RUNNING:
- throw newIllegalStateException("Cannot execute task:"
- + " the taskis already running.");
- case FINISHED:
- throw newIllegalStateException("Cannot execute task:"
- + " the taskhas already been executed "
- + "(a task canbe executed only once)");
- }
- }
-
- mStatus = Status.RUNNING;
-
- onPreExecute();
-
- mWorker.mParams = params;
- sExecutor.execute(mFuture);
-
- return this;
- }
当任务正在执行或者已经完成,会抛出IllegalStateException,由此可知我们不能够重复调用execute(Params...params)方法。在提交任务到线程池之前,调用了onPreExecute()方法。然后才执行sExecutor.execute(mFuture)是任务提交到线程池。
前面我们说到,当任务的状态发生改变时(1、执行成功2、取消执行3、进度更新),工作线程会向UI线程的Handler传递消息。在AsyncTask中,InternalHandler是在UI线程上创建的,它接收来自工作线程的消息,实现代码如下:
AsyncTask.java
- private static class InternalHandler extends Handler {
- @SuppressWarnings({"unchecked","RawUseOfParameterizedType"})
- @Override
- public voidhandleMessage(Message msg) {
- AsyncTaskResult result =(AsyncTaskResult) msg.obj;
- switch (msg.what) {
- caseMESSAGE_POST_RESULT:
-
- result.mTask.finish(result.mData[0]);
- break;
- caseMESSAGE_POST_PROGRESS:
- result.mTask.onProgressUpdate(result.mData);
- break;
- caseMESSAGE_POST_CANCEL:
- result.mTask.onCancelled();
- break;
- }
- }
- }
当接收到消息之后,AsyncTask会调用自身相应的回调方法。
总结:
1、 AsyncTask的本质是一个静态的线程池,AsyncTask派生出的子类可以实现不同的异步任务,这些任务都是提交到静态的线程池中执行。
2、线程池中的工作线程执行doInBackground(mParams)方法执行异步任务
3、当任务状态改变之后,工作线程会向UI线程发送消息,AsyncTask内部的InternalHandler响应这些消息,并调用相关的回调函数