Android之AsyncTask消息机制

AsyncTask消息传递过程分析,从doinbackgroud到postresult…

AsyncTask使用

使用asyncTask必须继承使用,子类必须至少重载donInbackGroud和OnPostExecute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
...
publishProgress(...)
...
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
new DownloadFilesTask().execute(url1, url2, url3);

消息传递分析

由AsyncTask用法可知,通过new DownloadFilesTask().execute(url1, url2, url3)来执行AsyncTask。则分析DownloadFilesTask().execute的消息传递过程即可获得AsyncTask的消息传递过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    DownloadFilesTask是AsyncTask的子类
public AsyncTask() {
//创建一个工作线程实例,在里面实现call方法
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);//设置当前线程为调用状态,mTaskInvoked是一个原子级被更新的boolean变量
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//设置进程优先级
Result result = doInBackground(mParams);//将doInBackground(mParams)的返回值赋值给result
Binder.flushPendingCommands();//把当前线程即将发生的Binder命令送交给内核驱动
return postResult(result);//返回结果
}
};

mFuture = new FutureTask<Result>(mWorker) {
//当Task状态转变到isDone()时调用
@Override
protected void done() {
...
postResultIfNotInvoked(get());//get获取
...
}
};
}

对构造函数进行分析:

  1. mWorker是WorkerRunnable。WorkerRunnable声明了mParams为数组,实现了Callable接口。则子类需要实现call()方法。call方法调用了doInbackground,postresult。postResult(Result)函数把数据发送给Handler处理。

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
    private Result postResult(Result result) {
    @SuppressWarnings("unchecked")
    Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
        new AsyncTaskResult<Result>(this, result));//会将消息的Target设置为getHandler返回的对象
    message.sendToTarget();//把信息发送给有getTarget()指定的Handler
    return result;
    }
    Message的sendToTarget函数,把消息发送给getTarget指定的 Handler,getTarget的Handler通过getHandler获得。
    public void sendToTarget() {
        target.sendMessage(this);
    }
    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());//可知使用的是主线程Looper,消息会被传递到主线程队列中
        }
        @Override
        public void handleMessage(Message msg) {
                 ...
        }
    }     
    
  2. mFuture是FutureTask。FutureTask构造将实现Callable接口的类变成了FutureTask(既实现了Runnable接口又实现了Callable接口)类。

    1
    2
    3
    4
    5
    6
    public FutureTask(Callable<V> callable) {
    if (callable == null)
    throw new NullPointerException();
    this.callable = callable;
    this.state = NEW; // ensure visibility of callable
    }

对exectue函数分析

  1. 产生实例之后调用execute(Params…会开始执行线程,调用excuteOnExecutor,excuteOnExecutor包含sDefaultExecutor,sDefaultExecutor是执行器SERIAL_EXECUTOR。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor,params);//传递了执行器和参数
    }
    sDefaultExecutor定义如下,可知其是SERIAL_EXECUTOR
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    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() {
    ...
    r.run();
    ...
    }
    });
    ...
    }
    protected synchronized void scheduleNext() {
    if ((mActive = mTasks.poll()) != null) {
    THREAD_POOL_EXECUTOR.execute(mActive);
    }
    }
    }
  2. executeOnExector先执行了onPreExecute。然后调用了execute函数执行mFuture,实际上就是执行mFuture的run方法。即执行mWorkRunnable的run方法,然后执行doinbackgroud和postresult方法。PostResult(Result)会交由Handler处理,Handler会交给finish处理,finish会调用onPostExecute(result)处理结果。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,Params... params) {
    ...
    mStatus = Status.RUNNING;//标示任务为运行状态
    ...
    onPreExecute();//执行初始化方法在UI线程中执行
    ...
    mWorker.mParams = params;//将参数传递给工作线程
    exec.execute(mFuture);//执行器执行mFuture
    ...
    return this;
    }
    Handler的finish
    private void finish(Result result) {
    if (isCancelled()) {
    onCancelled(result);
    } else {
    onPostExecute(result);
    }
    mStatus = Status.FINISHED;
    }
  3. onProgressUpdate在InternalHandler的handleMessage中,发给Handler。

    1
    2
    3
    4
    5
    6
    7
        @WorkerThread
    protected final void publishProgress(Progress... values) {
    if (!isCancelled()) {
    getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
    }
    }

消息传递简图

AsyncTask消息传递

-------------本文结束感谢您的阅读-------------
鼓励鼓励!