AsyncTask使用及分析
2017-04-21 本文已影响195人
篱开罗
AsyncTask基本用法
AsyncTask是一个抽象类,我们需要创建一个子类继承
它才可以使用
AsyncTask有三个泛型参数
public abstract class AsyncTask<Params, Progress, Result> {
Params
执行后台任务时传入的参数类型
Progress
后台任务执行进度的类型
Result
后台任务执行完毕返回的结果类型
基本用法
private class DownLoad extends AsyncTask<String, Integer, Boolean> {
//执行后台任务前的准备操作,在主线程执行
@Override
protected void onPreExecute() {
showDownloadDialog();
}
//执行的后台任务,在子线程执行
@Override
protected Boolean doInBackground(String... params) {
String url = params[0];
boolean result;
//判断任务是否被取消,防止取消后继续执行浪费资源
for (int i = 0; i < 5 && !isCancelled(); i++) {
try {
//模拟下载,每秒完成20%
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//调用onProgressUpdate,将进度传回主线程
publishProgress(20);
}
}
result = true;
return result;
}
//在主线程执行,进度变化时会被调用
//values为publishProgress(20)返回的参数
@Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(
mProgressDialog.getProgress() + values[0]);
}
//在主线程执行,任务执行结束时候调用
//result为doInBackground返回的结果
@Override
protected void onPostExecute(Boolean result) {
if (result) {
setText("success");
} else {
setText("failed");
}
}
}
执行
new DownLoad().execute("url");
源码分析
execute()方法
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
//sDefaultExecutor类似于一个串行的线程池
//进程中所有的AsyncTask都在该线程池中排队执行
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
//正在运行的AsyncTask不能重复运行
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
//每个AsyncTask实例只能运行一次
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
//我们之前重写的方法,最先执行,做一些准备工作
onPreExecute();
//mWorker是一个实现了Callable接口的对象,并将params参数包装进去
//doInBackground也封装进了mWorker
mWorker.mParams = params;
//mFutrue是FutureTask的对象,FutureTask的构造函数将mWorker传进去
//此处的exec默认是sDefaultExecutor,即SerialExecutor的对象
exec.execute(mFuture);
return this;
}
SerialExecutor内部类
private static class SerialExecutor implements Executor {
//AsyncTask的双向队列
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
//将AsyncTask中的任务入队
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
//当一个任务执行完则取出下一个AsyncTask对象的任务执行
//直到任务队列为空
//所以默认是串行执行的
scheduleNext();
}
}
});
//当前是否有活动的任务,否则取出一个任务并执行
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//取出活动并执行
if ((mActive = mTasks.poll()) != null) {
//真正执行任务的线程池
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
THREAD_POOL_EXECUTOR对象的构建
//CPU核心数
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//核心线程数最多4个最少2个
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
//线程池最大线程数
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//线程超时时间
private static final int KEEP_ALIVE_SECONDS = 30;
//线程工厂,提供创建新线程的功能
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
//等待队列,没有空闲的核心线程时任务会进入等待队列,等待队列满时且未达到最大线程数会启用一个非核心线程执行任务
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
public static final Executor THREAD_POOL_EXECUTOR;
static {
//初始化
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
mWorker对象
//WorkerRunnable实现了Callable接口
mWorker = new WorkerRunnable<Params, Result>() {
//mFuture中的run方法会调用mWorker的call方法,所以call方法会在线程池中执行
public Result call() throws Exception {
//表示当前任务已经被调用过了
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//执行我们重写的doInBackground方法
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//将执行任务得到的结果传送到主线程的Handler
postResult(result);
}
return result;
}
};
postResult()方法
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
//通过主线程获取Message,并设置Message的what和obj
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
//发送message
message.sendToTarget();
return result;
}
private static Handler getHandler() {
//单例模式获取Handler
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
InternalHandler类
private static class InternalHandler extends Handler {
public InternalHandler() {
//将该handler与主线程的looper绑定
super(Looper.getMainLooper());
}
public void handleMessage(Message msg) {
//AsyncTaskResult类封装了执行的任务和执行结果
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
//任务执行结束则调用finish()方法
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//调用我们重写的onProgressUpdate()方法
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private void finish(Result result) {
//根据当前任务是否被取消调用不同的方法
if (isCancelled()) {
//我们之前重写的onCancelled
onCancelled(result);
} else {
//我们之前重写的onPostExecute
onPostExecute(result);
}
//设置状态,如果再次运行该AsyncTask对象将抛出异常
mStatus = Status.FINISHED;
}
AsyncTask使用须知
-
AsyncTask默认是串行执行,若要并发执行则要调用
executeOnExecutor(Executor exec, Params... params)方法指定线程池执行
也可以通过setDefaultExecutor(Executor exec)设置默认线程池 -
AsyncTask作为内部类的时候最好声明为静态内部类,并以弱引用的形式引用Activity,防止内存泄漏
-
AsyncTask中的后台任务应该使用isCancelled()判断任务是否已经取消,防止做无用功,
任务中有一个循环,可以在循环条件中加入判断 -
Activity销毁的时候最好调用AsyncTask的cancel()方法,防止更新已经被回收的view
-
Activity重建时候应注意对AsyncTask的维护
Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案
reference
-
《Android开发艺术探索》