Android的AsyncTask类是处理异步任务的工具类,使程序员不用new Thread,不用写handler,只要使用AsyncTask类就能实现异步任务的处理了,但是不能说只用AsyncTask类而不要handler了,因为AsyncTask类在源码实现时,起的是一个线程池,在这个线程池中会有一定数量的线程。
AsyncTask类部分源码:
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
所以,在使用AsyncTask类时,不能盲目。。
参看AsyncTask类的源码,下面是模拟AsyncTask类功能的代码,就是把new Thread() 和 handler封装在一起。。。
package com.wang.mobilesafe.utils;
import android.os.Handler;
/**
* 模拟android的AsyncTask类
*
* 一个异步任务的工具类
*
* 模板设计模式
* @author HeJW
*
*/
public abstract class MyAsyncTask {
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
onPostExecute();
};
};
/**
* 耗时任务开始之前执行的方法
*/
public abstract void onPreExecute();
/**
* 耗时任务执行之后调用的方法
*/
public abstract void onPostExecute();
/**
* 执行的耗时任务,运行在子线程中
*/
public abstract void doInBackground();
/**
* 执行任务
*/
public void execute(){
onPreExecute();
new Thread(){
public void run() {
doInBackground();
handler.sendEmptyMessage(0);
};
}.start();
}
}