Asynctask源码级解析,深度探索源码之旅

来源:互联网 发布:知敬畏守规矩发言稿 编辑:程序博客网 时间:2024/05/24 01:19

常用方法:

1、onPreExecute方法是预加载,在主线程中执行

2、doInBackground运行在子线程中,执行耗时的操作,子线程中不能更新主UI界面

3、onProgressUpdate方法进度更新,运行在主线程中

4、onPostExecute结果处理,运行在主线程中,可以直接更新主UI

总结:Asynctask是通过线程池的原理来异步处理任务的,但在底层它的子线程是由java.util.concurrent包下的Callable接口子类实现的。

doInBackground是在Callable的实现类中回调的,所以执行在子线程中,而onProgressUpdate和onPostExecute两个方法是在handler中回调的因此执行在主线程,onPreExecute方法直接在父类中回调,所以也执行在主线程。

注意:子线程不能更新主线程UI

 

为什么呢?那就来看一下源码:

1、先看看onPreExecute在哪里被回调的。

public finalAsyncTask<Params, Progress,Result> executeOnExecutor(Executorexec,

           Params... params) {

       if (mStatus != Status.PENDING) {

           switch (mStatus) {

                case RUNNING:

                    throw newIllegalStateException("Cannot execute task:"

                            + " the taskis already running.");

                case FINISHED:

                    throw newIllegalStateException("Cannot execute task:"

                            + " the taskhas already been executed "

                            + "(a task canbe executed only once)");

           }

       }

 

       mStatus = Status.RUNNING;

 

       onPreExecute();//方法回调

 

       mWorker.mParams = params;

       exec.execute(mFuture);

 

       return this;

}

结论:显然该方法不运行在子线程中

参数含义拓展:


第一参数Executor是一个线程池

An object that executes submitted Runnabletasks. This interface provides a way of decoupling task submission from themechanics of how each task will be run, including details of thread use,scheduling, etc. AnExecutor is normally used instead of explicitly creating threads. Forexample, rather than invokingnew Thread(new(RunnableTask())).start()for each of a set of tasks, you might use:

2、doInBackground运行在子线程中,执行耗时的操作,子线程中不能更新主UI界面

mWorker = new WorkerRunnable<Params,Result>() {

     publicResult call() throws Exception {

        mTaskInvoked.set(true);

        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

        //noinspection unchecked

        return postResult(doInBackground(mParams));//方法回调

     }

private staticabstract class WorkerRunnable<Params,Result>implements Callable<Result> {

        Params[] mParams;

    }

英文版:


结论:显然该方法运行在子线程中,但原理不是Runnable接口,而是运行在和相似的Callable接口的实现类中。这两个接口属于不同的包,以及其他区别。

3、onProgressUpdate方法进度更新,运行在主线程中

 

    privatestatic class InternalHandler extends Handler {

       @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]);//finish方法回调

                    break;

                case MESSAGE_POST_PROGRESS:

                   result.mTask.onProgressUpdate(result.mData);//源码方法回调

                    break;

           }

       }

}

因为handler运行在主线程而onProgressUpdate方法在handler中回调,所以onProgressUpdate方法运行在主线程,因此可以和主线程交互。

 

4、onPostExecute方法

private void finish(Result result) {

        if (isCancelled()) {

            onCancelled(result);

        } else {

            onPostExecute(result);//方法回调

        }

        mStatus = Status.FINISHED;

}

 

0 0
原创粉丝点击