之前写过一篇Handler的源码解析文章,因为AsyncTask底层也是Handler实现的,所以不了解的可以先去了解下Handler。本文也会再次分析下Handler,毕竟它是android源码中随处可见的东东。
一、Handler的简要分析
讲Handler之前我们先讲一下ThreadLocal的概念。简单的说,ThreadLocal是介于局部变量和全局变量之间,可以在不同线程中互不干扰地存储并提供数据。也就是说,变量a在A线程中值与在B线程中值可能是不同的。它通过get()和set()方法来获取和存储变量。
由于之前分析过Handler,在这里就大概的介绍,Handler底层是由MessageQueue和Looper去支撑。Looper可以理解为一个中介,负责论询MessageQueue中的消息,并它消息传给Handler进行处理。MessageQueue内部存储结构是一个单链表,可以快速的插入和删除。
在ActivityThread启动过程中就会创建Looper并存放在ThreadLocal中,在Handler的构造方法中就会通过Looper.myLooper()去ThreadLocal中获取该线程的Looper,接下来调用looper.prepare()方法,在该方法中创建MessageQueue,在 handler调用post或者sendMessage()时,就会调用enqueueMessage把消息存到单链表中,而looper.loop()方法其实就是一个死循环,一直在论询MessageQueue,如果获得到消息就调用target(其实就是handler)的dispatchMessage()并调用 handleMessage()进行消息处理。以上就是Handler的源码流程,如果感兴趣可以自行去跟一下。这里有一点需要强调下,就是在处理dispatchMessage()时,它的源码如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
只有当callback为空时才会调用handleMessage,否则调用callback.handleMessage()。这里也给我们提供了一个思路,可以通过
callback来拦截消息,比如以下代码:
private Handler H = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if(msg.what == 0x11){
return true;
}else{
return false;
}
}}) {
@Override
public void handleMessage(Message msg) {
//处理相应业务
};
这相当msg的what是0x11时,就不会再执行handleMessage了。
使用Handler有一点非常重要的,如果是在子线程使用,那需要手动的添加looper.prepare()和looper.loop()方法。而子线程handler的handleMessage也是在子线程中处理,这点需要处理。
二,HandlerThread
上面即然说到在子线程中使用Handler,那我们就来说下HandlerThread,HandlerThread其实就是一个封装好Thread,它可以使用Handler,之所以不提倡在子线程中直接使用Handler是因为它存在并发的问题。也就是说Handler在创建时需要获取Looper对象,但此时可能Thread还没有跑到Looper.prepare()那一步,那就会报空指针异常,看到这里我们第一反应肯定是那就用wait()和notifyAll()来实现啊。是的,HandlerThread就是加入了这两个元素,不信可以翻下源码:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
HandlerThread在调用getLooper时,如果还不存在,就wait(),它本身是一个Thread,它在run方法创建完就会调用notifyAll(),这样getLooper就会继续执行。就这么简单。实现代码如下:
HandlerThread thread = new HandlerThread("handler");
thread.start();
Handler h = new Handler(thread.getLooper()){
@Override
public void handleMessage(Message msg) {
//处理相应业务
};
};
h.sendEmptyMessage(0X11);
三,AsyncTask源码分析
上面说了那么多,都是在消息处理机制,感觉有点跑题了,囧。。。接下来就来分析下AsyncTask,终于进入正题了。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls. length;
long totalSize = 0;
for ( int i = 0; i < count; i++) {
// totalSize += Downloader.downloadFile(urls[i]);
publishProgress(( int) ((i / ( float) count) * 100));
// Escape early if cancel() is called
if (isCancelled())
break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
// showDialog("Downloaded " + result + " bytes");
}
}
好啦 ,讲完用法,来分析下它的源码吧!!
2.源码分析
从它的execute方法入手。
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
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.mParams = params;
exec.execute(mFuture);
return this;
}
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
<pre name="code" class="java">public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
看到这里就明白了,它的底层还是Handler。这里就不再分析Handler了。
主要找到handler,看getHandler()的方法。
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
很直然就进入InternalHandler()。
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
两种情况,一种是运行结束,调用finish,一种是还没结束,调用onProgressUpdate传入进度值。是不是一下子就把三个方法串起来了。好了,到这里AsyncTask的源码就分析完了。
好啦 ,就写到这吧。