AsyncTask原理及相关原则

作者: 小红军storm | 来源:发表于2019-02-25 18:14 被阅读4次

    1、AsyncTask类的四个抽象方法

    public abstract class AsyncTask<Params, Progress, Result> {
    
       /**
       Runs on the UI thread before {@link #doInBackground}.
       */
        @MainThread
        protected void onPreExecute() {
        }
    
       /**
         * Override this method to perform a computation on a background thread. 
         * This method can call {@link #publishProgress} to publish updates
         * on the UI thread.
         **/
        @WorkerThread
        protected abstract Result doInBackground(Params... params);
    
    
        /**
         * Runs on the UI thread after {@link #publishProgress} is invoked.
         * The specified values are the values passed to {@link #publishProgress}.
         */
        @SuppressWarnings({"UnusedDeclaration"})
        @MainThread
        protected void onProgressUpdate(Progress... values) {
        }
    
    
         /**
         * <p>Runs on the UI thread after {@link #doInBackground}. The
         * specified result is the value returned by {@link #doInBackground}.</p>
         This method won't be invoked if the task was cancelled.</p>
         */
        @SuppressWarnings({"UnusedDeclaration"})
        @MainThread
        protected void onPostExecute(Result result) {
        }
    
    }
    

    2、AsyncTask的执行流程

    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
            return executeOnExecutor(sDefaultExecutor, params);
        }
    

    当我们构造一个AsyncTask的子类,并调用其execute方法时,execute方法会调用executeOnExecutor,并向其传递一个SERIAL_EXECUTOR和我们execute中的传递的参数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;
        }
    

    executeOnExecutor中,首先会调用AyncTask中的第一个回调方法onPreExecute,然后将我们的我们的参数params封装在AsyncTask构建时创建的一个FutureTask中,然后使用SERIAL_EXECUTOR去执行这个FutureTask,

     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);
                }
            }
        }
    

    SERIAL_EXECUTOR是负责将所有的FutureTask加入到一个ArrayDeque的队列中进行排队,(在FutureTask加入到ArrayDeque之前会构造一个runnable,在这个runnable的run方法中首先会调用FutureTask的run方法,然后在其finally模块中调用了scheduleNext方法),如果当前没有一个任务正在运行,就调用scheduleNext从任务队列ArrayDeque中取出一个任务,使THREAD_POOL_EXECUTOR对这个任务进行执行。

    mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
                    Result result = null;
                    try {
                        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                        //noinspection unchecked
                        result = doInBackground(mParams);
                        Binder.flushPendingCommands();
                    } catch (Throwable tr) {
                        mCancelled.set(true);
                        throw tr;
                    } finally {
                        postResult(result);
                    }
                    return result;
                }
            };
    

    实际上就是调用了FutureTask的run方法,在FutureTask的run方法中又会调用构造它的WorkerRunnable的call方法,在WorkerRunnable的call方法中首先会调用doInBackground方法获取任务结果,(这个doInBackground是在THREAD_POOL_EXECUTOR执行的,所以可以在里面做一些耗时操作),然后调用postResult将这个结果发送出去。

    private Result postResult(Result result) {
            @SuppressWarnings("unchecked")
            Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskResult<Result>(this, result));
            message.sendToTarget();
            return result;
        }
    

    在postResult中,通过一个InternalHandler(InternalHandler在AsyncTask的构造方法中初始化,所以要想消息发送到主线程,AsyncTask必须在主线程中初始化)对result进行封装,然后发送出去。

    private static class InternalHandler extends Handler {
            public InternalHandler(Looper looper) {
                super(looper);
            }
    
            @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;
                }
            }
        }
    

    在InternalHandler的handleMessage的result分支中调用了finish方法,在finish方法中,如果任务取消,就调用onCancelled方法,否则调用onPostExecute。
    在doInBackground中调用publishProgress发布进度和结果的发布类似,都是通过InternalHandler构造一个message,然后将这个message发送到主线程中处理,在InternalHandler的progress分支调用onProgressUpdate。

    3、AyncTask中四大原则原因

    1、The AsyncTask class must be loaded on the UI thread. This is done
    automatically as of android.os.Build.VERSION_CODES#JELLY_BEAN.

    2、The task instance must be created on the UI thread.
    在AsyncTask中会初始化InternalHandler,如果不是在主线程中,将无法获取主线程的looper,执行结果也无法发送到主线程。(新版错误)
    新版初始化InternalHandler的looper是Looper.getMainLooper(),所以InternalHandler中的事件总是在主线程中处理。

    正确的回答是execute方法需要在主线程中调用,进而AsyncTask实例需要在主线程中创建。(如果在子线程中创建AsyncTask实例,将无法在主进程中调用execute方法)

    3、execute must be invoked on the UI thread.
    AsyncTask的execute(Params...)方法必须在UI线程中被调用,原因是在execute(Params...)方法中调用了onPreExecute()方法,onPreExecute()方法是在task开始前在UI线程进行若干准备工作,例如:初始化一个进度条等,所以必须要在UI线程下执行。

    4、Do not call onPreExecute()、onPostExecute、doInBackground、onProgressUpdate manually.

    5、The task can be executed only once (an exception will be thrown if
    a second execution is attempted.)
    一个AsyncTask实例只能被执行一次,这是为了线程安全,当AsyncTask在直接调用executeOnExecutor()方法进入并行模式时,避免同一个任务同时被执行而造成混乱。

    相关文章

      网友评论

        本文标题:AsyncTask原理及相关原则

        本文链接:https://www.haomeiwen.com/subject/vwibyqtx.html