Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1078055
  • 博文数量: 403
  • 博客积分: 10272
  • 博客等级: 上将
  • 技术积分: 4407
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:22
文章分类

全部博文(403)

文章存档

2012年(403)

分类: 嵌入式

2012-03-01 17:37:07

AsyncTask的本质是一个线程池,所有提交的异步任务都会在这个线程池(想想C3P0)中的工作线程内执行,当工作线程需要跟UI线程交互时,工作线程会通过向在UI线程创建的Handler传递消息的方式,调用相关的回调函数,从而实现UI界面的更新。

还是以昨天的例子为例~来说明AsyncTask的实现原理
Java代码 复制代码 收藏代码
  1. package cn.caiwb.aysnc;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.client.HttpClient;
  4. import org.apache.http.client.methods.HttpGet;
  5. import org.apache.http.impl.client.DefaultHttpClient;
  6. import android.app.Activity;
  7. import android.graphics.Bitmap;
  8. import android.graphics.BitmapFactory;
  9. import android.os.AsyncTask;
  10. import android.os.Bundle;
  11. import android.view.View;
  12. import android.view.View.OnClickListener;
  13. import android.widget.Button;
  14. import android.widget.ImageView;
  15. import android.widget.ProgressBar;
  16. import android.widget.Toast;
  17. public class AsyncTaskActivity extends Activity {
  18. private ImageView mImageView;
  19. private Button mButton;
  20. private ProgressBar mProgressBar;
  21. @Override
  22. public void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.main);
  25. mImageView= (ImageView) findViewById(R.id.imageView);
  26. mButton = (Button) findViewById(R.id.button);
  27. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  28. mButton.setOnClickListener(new OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. GetIteyeLogoTask task = new GetIteyeLogoTask();
  32. task.execute("http://www.iteye.com/images/logo.gif");
  33. }
  34. });
  35. }
  36. class GetIteyeLogoTask extends AsyncTask {//继承AsyncTask
  37. @Override
  38. protected Bitmap doInBackground(String... params) {//处理后台执行的任务,在后台线程执行
  39. publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法
  40. HttpClient hc = new DefaultHttpClient();
  41. publishProgress(30);
  42. HttpGet hg = new HttpGet(params[0]);//获取csdn的logo
  43. final Bitmap bm;
  44. try {
  45. HttpResponse hr = hc.execute(hg);
  46. bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
  47. } catch (Exception e) {
  48. return null;
  49. }
  50. publishProgress(100);
  51. //mImageView.setImageBitmap(result); 不能在后台线程操作ui
  52. return bm;
  53. }
  54. protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用,在ui线程执行
  55. mProgressBar.setProgress(progress[0]);//更新进度条的进度
  56. }
  57. protected void onPostExecute(Bitmap result) {//后台任务执行完之后被调用,在ui线程执行
  58. if(result != null) {
  59. Toast.makeText(AsyncTaskActivity.this, "成功获取图片", Toast.LENGTH_LONG).show();
  60. mImageView.setImageBitmap(result);
  61. }else {
  62. Toast.makeText(AsyncTaskActivity.this, "获取图片失败", Toast.LENGTH_LONG).show();
  63. }
  64. }
  65. protected void onPreExecute () {//在 doInBackground(Params...)之前被调用,在ui线程执行
  66. mImageView.setImageBitmap(null);
  67. mProgressBar.setProgress(0);//进度条复位
  68. }
  69. protected void onCancelled () {//在ui线程执行
  70. mProgressBar.setProgress(0);//进度条复位
  71. }
  72. }
  73. }
package cn.caiwb.aysnc; 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.main); mImageView= (ImageView) findViewById(R.id.imageView); mButton = (Button) findViewById(R.id.button); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { GetIteyeLogoTask task = new GetIteyeLogoTask(); task.execute("http://www.iteye.com/images/logo.gif"); } }); } class GetIteyeLogoTask extends AsyncTask {//继承AsyncTask @Override protected Bitmap doInBackground(String... params) {//处理后台执行的任务,在后台线程执行 publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法 HttpClient hc = new DefaultHttpClient(); publishProgress(30); HttpGet hg = new HttpGet(params[0]);//获取csdn的logo final Bitmap bm; try { HttpResponse hr = hc.execute(hg); bm = BitmapFactory.decodeStream(hr.getEntity().getContent()); } catch (Exception e) { return null; } publishProgress(100); //mImageView.setImageBitmap(result); 不能在后台线程操作ui return bm; } protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用,在ui线程执行 mProgressBar.setProgress(progress[0]);//更新进度条的进度 } protected void onPostExecute(Bitmap result) {//后台任务执行完之后被调用,在ui线程执行 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 () {//在 doInBackground(Params...)之前被调用,在ui线程执行 mImageView.setImageBitmap(null); mProgressBar.setProgress(0);//进度条复位 } protected void onCancelled () {//在ui线程执行 mProgressBar.setProgress(0);//进度条复位 } } }

分析:

在分析实现流程之前,我们先了解一下AsyncTask有哪些成员变量。

Java代码 复制代码 收藏代码
  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 sWorkQueue =
  5. new LinkedBlockingQueue(10);//等待队列
  6. private static final ThreadPoolExecutor***ecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
  7. MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue,sThreadFactory);//线程池是静态变量,所有的异步任务都会放到这个线程池的工作线程内执行。
private static final int CORE_POOL_SIZE =5;//5个核心工作线程 private static final int MAXIMUM_POOL_SIZE = 128;//最多128个工作线程 private static final int KEEP_ALIVE = 1;//空闲线程的超时时间为1秒 private static final BlockingQueue sWorkQueue = new LinkedBlockingQueue(10);//等待队列 private static final ThreadPoolExecutor***ecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue,sThreadFactory);//线程池是静态变量,所有的异步任务都会放到这个线程池的工作线程内执行。


回到例子中,点击按钮之后会新建一个GetIteyeLogoTask对象:

Java代码 复制代码 收藏代码
  1. GetIteyeLogoTask task = new GetIteyeLogoTask();
GetIteyeLogoTask task = new GetIteyeLogoTask();

此时会调用父类AsyncTask的构造函数:

AsyncTask.java

Java代码 复制代码 收藏代码
  1. public AsyncTask() {
  2. mWorker = new WorkerRunnable() {
  3. public Result call() throws Exception {
  4. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
  5. return doInBackground(mParams);
  6. }
  7. };
  8. mFuture = new FutureTask(mWorker) {
  9. @Override
  10. protected void done() {
  11. Message message;
  12. Result result = null;
  13. try {
  14. result = get();
  15. } catch (InterruptedException e) {
  16. android.util.Log.w(LOG_TAG, e);
  17. } catch (ExecutionException e) {
  18. throw new RuntimeException("An error occured while executing doInBackground()",
  19. e.getCause());
  20. } catch (CancellationException e) {
  21. message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
  22. new AsyncTaskResult(AsyncTask.this, (Result[]) null));
  23. message.sendToTarget();//取消任务,发送MESSAGE_POST_CANCEL消息
  24. return;
  25. } catch (Throwable t) {
  26. throw new RuntimeException("An error occured while executing "
  27. + "doInBackground()", t);
  28. }
  29. message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
  30. new AsyncTaskResult(AsyncTask.this, result));//完成任务,发送MESSAGE_POST_RESULT消息并传递result对象
  31. message.sendToTarget();
  32. }
  33. };
  34. }
public AsyncTask() { mWorker = new WorkerRunnable() { public Result call() throws Exception { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return doInBackground(mParams); } }; mFuture = new FutureTask(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(AsyncTask.this, (Result[]) null)); message.sendToTarget();//取消任务,发送MESSAGE_POST_CANCEL消息 return; } catch (Throwable t) { throw new RuntimeException("An error occured while executing " + "doInBackground()", t); } message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult(AsyncTask.this, result));//完成任务,发送MESSAGE_POST_RESULT消息并传递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)和任务状态变化后的操作(包括失败和成功)。

当创建完GetIteyeLogoTask对象后,执行

Java代码 复制代码 收藏代码
  1. task.execute("http://www.iteye.com/images/logo.gif");
task.execute("http://www.iteye.com/images/logo.gif");

此时会调用AsyncTask的execute(Params...params)方法

Java代码 复制代码 收藏代码
  1. public final AsyncTask execute(Params... params) {
  2. if (mStatus != Status.PENDING) {
  3. switch (mStatus) {
  4. case RUNNING:
  5. throw newIllegalStateException("Cannot execute task:"
  6. + " the taskis already running.");
  7. case FINISHED:
  8. throw newIllegalStateException("Cannot execute task:"
  9. + " the taskhas already been executed "
  10. + "(a task canbe executed only once)");
  11. }
  12. }
  13. mStatus = Status.RUNNING;
  14. onPreExecute();//运行在ui线程,在提交任务到线程池之前执行
  15. mWorker.mParams = params;
  16. ***ecutor.execute(mFuture);//提交任务到线程池
  17. return this;
  18. }
public final AsyncTask 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();//运行在ui线程,在提交任务到线程池之前执行 mWorker.mParams = params; ***ecutor.execute(mFuture);//提交任务到线程池 return this; }

当任务正在执行或者已经完成,会抛出IllegalStateException,由此可知我们不能够重复调用execute(Params...params)方法。在提交任务到线程池之前,调用了onPreExecute()方法。然后才执行***ecutor.execute(mFuture)是任务提交到线程池。

前面我们说到,当任务的状态发生改变时(1、执行成功2、取消执行3、进度更新),工作线程会向UI线程的Handler传递消息。我们知道Handler要处理其他线程传递过来的消息。在AsyncTask中,InternalHandler是在UI线程上创建的,它接收来自工作线程的消息,实现代码如下:

Java代码 复制代码 收藏代码
  1. private static class InternalHandler extends Handler {
  2. @SuppressWarnings({"unchecked","RawUseOfParameterizedType"})
  3. @Override
  4. public voidhandleMessage(Message msg) {
  5. AsyncTaskResult result =(AsyncTaskResult) msg.obj;
  6. switch (msg.what) {
  7. caseMESSAGE_POST_RESULT:
  8. // There is onlyone result
  9. result.mTask.finish(result.mData[0]);//执行任务成功
  10. break;
  11. caseMESSAGE_POST_PROGRESS:
  12. result.mTask.onProgressUpdate(result.mData);//进度更新
  13. break;
  14. caseMESSAGE_POST_CANCEL:
  15. result.mTask.onCancelled();//取消任务
  16. break;
  17. }
  18. }
  19. }
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: // There is onlyone 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响应这些消息,并调用相关的回调函数
阅读(561) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~