AsyncTask源码阅读

来源:互联网 发布:linux五笔输入法安装 编辑:程序博客网 时间:2024/05/21 09:58

execute 方法
最终调用executeOnExecutor(sDefaultExecutor, params)

@MainThread    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;    }

开始会调用我们自己实现的 onPreExecute() 然后通过exec.execute(mFuture) 的方式执行线程

构造过程

public AsyncTask() {        mWorker = new WorkerRunnable<Params, Result>() {            public Result call() throws Exception {                mTaskInvoked.set(true);                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);                //noinspection unchecked                Result result = doInBackground(mParams);                Binder.flushPendingCommands();                return postResult(result);            }        };        mFuture = new FutureTask<Result>(mWorker) {            @Override            protected void done() {                try {                    postResultIfNotInvoked(get());                } catch (InterruptedException e) {                    android.util.Log.w(LOG_TAG, e);                } catch (ExecutionException e) {                    throw new RuntimeException("An error occurred while executing doInBackground()",                            e.getCause());                } catch (CancellationException e) {                    postResultIfNotInvoked(null);                }            }        };    }

mWorker 其实是callable类型 (与线程相关的一个类) 在该对象构造中调用了 我们自己实现的doInBackground(mParams); 然后调用了Binder.flushPendingCommands(); 将线程发送到内核, 最后 postResult() 发送消息给handler.

然后创建FutureTask 对象 (与线程相关的类) 调用了postResultIfNotInvoked(get()); 作用与上面一样 都调用了postResult() 只是需要在 !wasTaskInvoked 的情况下调用

0 0