美文网首页
AsyncTask使用总结及源码分析

AsyncTask使用总结及源码分析

作者: Mr韶先生 | 来源:发表于2017-03-17 15:40 被阅读33次

    AsyncTask

    AsyncTask是android再API-3中加入的类,为了方便开发人员执行后台操作并在UI线程上发布结果而无需操作Threads和handlers。AsyncTask的设计是围绕Threads和handlers的一个辅助类,不构成一个通用的线程框架。其用于时间较短的网络请求,例如登录请求。对于下载文件这种长时间的网络请求并不合适。
     AsyncTask是一个抽象类,使用时必须继承AsyncTask并实现其protected abstract Result doInBackground(Params... params);方法。在继承时可以为AsyncTask类指定三个泛型参数,这三个参数的用途如下:

    1. Params
      在执行AsyncTask时需要传入的参数,可用于在后台任务中使用。
    2. Progress
      后台任何执行时,如果需要在界面上显示当前的进度,则使用这里指定的泛型作为进度单位。
    3. Result
      当任务执行完毕后,如果需要对结果进行返回,则使用这里指定的泛型作为返回值类型。

    举个例子:

    public class MainActivity extends AppCompatActivity{
        private static final String TAG = "MainActivity";
        private ProgressDialog mDialog;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mDialog = new ProgressDialog(this);
            mDialog.setMax(100);
            mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDialog.setCancelable(false);
    
            new myAsycnTask().execute();
    
        }
        private  class myAsycnTask extends AsyncTask<Void,Integer,Void>{
            @Override
            protected void onPreExecute() {
               //执行任务之前,准备操作
                super.onPreExecute();
                mDialog.show();
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                //任务执行过程中 
                for (int i =0 ;i<100;i++)
                {
                    SystemClock.sleep(100);
                    publishProgress(i);
                }
                return null;
            }
            @Override
            protected void onProgressUpdate(Integer... values) {
               //任务执行过程中更新状态
                super.onProgressUpdate(values);
                mDialog.setProgress(values[0]);
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                //任务执行完成之后
                super.onPostExecute(aVoid);
                mDialog.dismiss();
            }
        }
    }
    

    AsyncTask 异步加载数据可能需要重写以下几个方法:

    1. onPreExecute()
      这个方法会在后台任务开始执行之间调用,用于进行一些的初始化操作。
    2. doInBackground(Params...)
      子类必须重写该方法,这个方法中的所有代码都会在子线程中执行,处理耗时任务。任务完成后可以通过return语句将结果返回,如果AsyncTask的第三个泛型参数指定的是Void,就可以不返回任务执行结果。在这个方法中不可以进行UI操作,如果需要更新UI元素,可以调用publishProgress(Progress...)方法来完成。
    3. onProgressUpdate(Progress...)
      当在doInBackground(Params...)中调用了publishProgress(Progress...)方法后,会调用该方法,参数为后台任务中传递过来Progress...。在这个方法中可以对UI进行操作,利用参数中的数值就可以对UI进行相应的更新。
    4. onPostExecute(Result)
      当后台任务执行完毕并通过 return语句进行返回时,方法会被调用。返回的数据会作为参数传递到此方法中,可以利用返回的数据来进行一些UI操作。

    通过调用cancel(boolean)方法可以随时取消AsyncTask任务,调用该方法之后会随后调用iscancelled()并返回true,doInBackground(Object[])返回之后会直接调用onCancelled(Object)方法而不是正常调用时的onPostExecute(Result)

    注意:

    1、AsyncTask必须在UI线程。
     2、必须在UI线程上创建任务实例。
     3、execute(Params...) 必须在UI线程中调用。
     4、不要手动调用onpreexecute(),onpostexecute(Result),doInBackground(Params…),onProgressUpdate(Progress…)这些方法。
     5、任务只能执行一次(如果尝试执行第二次执行将抛出异常)。

    使用AsyncTask不需要考虑异步消息处理机制,也不需要考虑UI线程和子线程,只需要调用一下publishProgress()方法就可以轻松地从子线程切换到UI线程了。从android 3.0之后AsyncTask使用单线程处理所有任务。

    AsyncTask源码分析

    我们使用AsyncTask时,new了一个myAsycnTask对象然后执行了execute()方法new myAsycnTask().execute(); 。那就先看一下AsyncTask的构造函数和execute()方法:

     /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            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;
                }
            };
    
            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);
                    }
                }
            };
        }
    /**
         * Executes the task with the specified parameters. The task returns
         * itself (this) so that the caller can keep a reference to it.
         */
        @MainThread
        public final AsyncTask<Params, Progress, Result> execute(Params... params) {
            return executeOnExecutor(sDefaultExecutor, params);
        }
    
     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
            Params[] mParams;
        }
    /**
         * Creates a {@code FutureTask} that will, upon running, execute the
         * given {@code Callable}.
         */
        public FutureTask(Callable<V> callable) {
            if (callable == null)
                throw new NullPointerException();
            this.callable = callable;
            this.state = NEW;       // ensure visibility of callable
        }
    
    

    构造函数中初始化了两个参数,在mWorker中进行了初始化操作,并在初始化mFuture的时候将mWorker作为参数传入。mWorker是一个实现了Callable<Result>接口的Callable对象,mFuture是一个FutureTask对象,创建时设置了mWorker的回调方法,然后设置状态为this.state = NEW; (该状态是FutureTask类中的) 。

        @MainThread
        public final AsyncTask<Params, Progress, Result> execute(Params... params) {
            return 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;
        }
    
      /**
         * Indicates the current status of the task. Each status will be set only once
         * during the lifetime of a task.
         */
        public enum Status {
            /**
             * Indicates that the task has not been executed yet.
             */
            PENDING,
            /**
             * Indicates that the task is running.
             */
            RUNNING,
            /**
             * Indicates that {@link AsyncTask#onPostExecute} has finished.
             */
            FINISHED,
        }
    

    可以看到execute()方法调用了executeOnExecutor(sDefaultExecutor, params)方法,该方法中,首先检查当前任务状态, PENDING,代表任务还没有执行;RUNNING,代表任务正在执行;FINISHED,代表任务已经执行完成。如果任务没有执行,设置当前状态为正在执行,调用了onPreExecute();方法,因此证明了onPreExecute()方法会第一个得到执行。那doInBackground(Void... params)在什么地方调用的呢?看方法最后执行了exec.execute(mFuture);,这个exec就是execute(Params... params)中传过来的sDefaultExecutor参数,让我们分析一下它做了什么。

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    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);
                }
            }
        }
    

    可以看到sDefaultExecutor是一个SerialExecutor对象,其execute(final Runnable r)方法中的r就是exec.execute(mFuture);中的mFuture
    SerialExecutor是使用ArrayDeque这个队列来管理Runnable对象的,如果一次性启动多个任务,在第一次运行execute()方法的时候,会调用ArrayDequeoffer()方法将传入的Runnable对象添加到队列的尾部,然后判断mActive对象是不是等于null,第一次运行是等于null的,于是会调用scheduleNext()方法。在这个方法中会从队列的头部取值,并赋值给mActive对象,然后调用THREAD_POOL_EXECUTOR去执行取出的取出的Runnable对象。之后如何又有新的任务被执行,同样还会调用offer()方法将传入的Runnable添加到队列的尾部,但是再去给mActive对象做非空检查的时候就会发现mActive对象已经不再是null了,于是就不会再调用scheduleNext()方法。
     那么后面添加的任务岂不是永远得不到处理了?当然不是,看一看offer()方法里传入的Runnable匿名类,这里使用了一个try finally代码块,并在finally中调用了scheduleNext()方法,保证无论发生什么情况,这个方法都会被调用。也就是说,每次当一个任务执行完毕后,下一个任务才会得到执行,SerialExecutor模仿的是单一线程池的效果,如果我们快速地启动了很多任务,同一时刻只会有一个线程正在执行,其余的均处于等待状态

    看看它在子线程里做了什么:

    private Callable<V> callable;
    ublic FutureTask(Callable<V> callable) {
            if (callable == null)
                throw new NullPointerException();
            this.callable = callable;
            this.state = NEW;       // ensure visibility of callable
        }
    public void run() {
            if (state != NEW ||
                !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
                return;
            try {
                Callable<V> c = callable;
                if (c != null && state == NEW) {
                    V result;
                    boolean ran;
                    try {
                        result = c.call();
                        ran = true;
                    } catch (Throwable ex) {
                        result = null;
                        ran = false;
                        setException(ex);
                    }
                    if (ran)
                        set(result);
                }
            } finally {
                // runner must be non-null until state is settled to
                // prevent concurrent calls to run()
                runner = null;
                // state must be re-read after nulling runner to prevent
                // leaked interrupts
                int s = state;
                if (s >= INTERRUPTING)
                    handlePossibleCancellationInterrupt(s);
            }
        }
    

    可以看到mFuture中的run()方法调用了构造函数中传过来的callable对象的call()方法,也就是AsyncTask的构造函数中的mWorkercall()方法,在这个方法中调用了result = doInBackground(mParams);

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

    终于找到了doInBackground()方法的调用处,虽然经过了很多周转,但目前的代码仍然是运行在子线程当中的,所以这也就是为什么我们可以在doInBackground()方法中去处理耗时的逻辑。
    call()在最后执行了postResult(result);函数,好的,继续往下看。

    private static Handler getHandler() {
            synchronized (AsyncTask.class) {
                if (sHandler == null) {
                    sHandler = new InternalHandler();
                }
                return sHandler;
            }
        }
    
    private Result postResult(Result result) {
            @SuppressWarnings("unchecked")
            Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskResult<Result>(this, result));
            message.sendToTarget();
            return result;
        }
    

    这段代码对是不是很熟悉?这里使用getHandler()返回的sHandler对象发出了一条消息,消息中携带了MESSAGE_POST_RESULT常量和一个表示任务执行结果的AsyncTaskResult对象。这个sHandler对象是InternalHandler类的一个实例,那么稍后这条消息肯定会在InternalHandler的handleMessage()方法中被处理。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;
                }
            }
        }
    

    可以看到,根据不同的消息进行了判断,如果是MESSAGE_POST_RESULT消息则执行result.mTask.finish(result.mData[0]);;如果是MESSAGE_POST_PROGRESS则执行result.mTask.onProgressUpdate(result.mData);,先让我们看看AsyncTaskResult<?> result到底是什么?

    @SuppressWarnings({"RawUseOfParameterizedType"})
        private static class AsyncTaskResult<Data> {
            final AsyncTask mTask;
            final Data[] mData;
    
            AsyncTaskResult(AsyncTask task, Data... data) {
                mTask = task;
                mData = data;
            }
        }
    

    可以看到``中包含两个参数,一个是AsyncTask当前的AsyncTask对象,一个是 Data[]返回数据的数组。所以result.mTask.finish(result.mData[0]);result.mTask.onProgressUpdate(result.mData);就是调用 AsyncTask的finsh和onProgressUpdate方法。让我们看一下:

    public final boolean cancel(boolean mayInterruptIfRunning) {
            mCancelled.set(true);
            return mFuture.cancel(mayInterruptIfRunning);
        }
     public final boolean isCancelled() {
            return mCancelled.get();
        }
    private void finish(Result result) {
            if (isCancelled()) {
                onCancelled(result);
            } else {
                onPostExecute(result);
            }
            mStatus = Status.FINISHED;
        }
    

    就像文章开头说的,任务可以随时取消,如果取消会调用isCancelled()返回true,并且onCancelled(result);会代替onPostExecute(result);执行。如果没有取消的话就会直接执行onPostExecute(result);方法。
     好了,还剩下publishProgress(Progress...)onProgressUpdate(Progress...)方法了。上面说到sHandler对象中有两种消息,还有一种是MESSAGE_POST_PROGRESS执行result.mTask.onProgressUpdate(result.mData);方法,让我们看一下publishProgress(Progress...)

    @WorkerThread
        protected final void publishProgress(Progress... values) {
            if (!isCancelled()) {
                getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                        new AsyncTaskResult<Progress>(this, values)).sendToTarget();
            }
        }
    

    非常明确了,在publishProgress(Progress...)方法中发送了MESSAGE_POST_PROGRESS然后在onProgressUpdate(Progress...)方法中对消息的数据进行了处理。正因如此,在doInBackground()方法中调用publishProgress()方法才可以从子线程切换到UI线程,从而完成对UI元素的更新操作。
     最后我们看一下取消任务是怎么实现的:

    //AsycnTask中的cancel方法
    public final boolean cancel(boolean mayInterruptIfRunning) {
            mCancelled.set(true);
            return mFuture.cancel(mayInterruptIfRunning);
        }
    
    //mFuture = new FutureTask<Result>(mWorker);类中的cancel方法
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (!(state == NEW &&
                  U.compareAndSwapInt(this, STATE, NEW,
                      mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
                return false;
            try {    // in case call to interrupt throws exception
                if (mayInterruptIfRunning) {
                    try {
                        Thread t = runner;
                        if (t != null)
                            t.interrupt();
                    } finally { // final state
                        U.putOrderedInt(this, STATE, INTERRUPTED);
                    }
                }
            } finally {
                finishCompletion();
            }
            return true;
        }
        private void finishCompletion() {
            // assert state > COMPLETING;
            for (WaitNode q; (q = waiters) != null;) {
                if (U.compareAndSwapObject(this, WAITERS, q, null)) {
                    for (;;) {
                        Thread t = q.thread;
                        if (t != null) {
                            q.thread = null;
                            LockSupport.unpark(t);
                        }
                        WaitNode next = q.next;
                        if (next == null)
                            break;
                        q.next = null; // unlink to help gc
                        q = next;
                    }
                    break;
                }
            }
    
            done();
    
            callable = null;        // to reduce footprint
        }
    

    可以看到当调用AsyncTask中的cancel(boolean mayInterruptIfRunning)方法时会传入一个boolean值,
    该值表示是否允许当前运行中的任务执行完毕,true代表不允许,false代表允许。然后调用了mFuture.cancel(mayInterruptIfRunning)方法,该方法中会判断mayInterruptIfRunning的值,如果为true则调用线程的interrupt();方法,中断请求,然后执行finishCompletion()方法;如果为false则直接执行finishCompletion()方法。finishCompletion()方法将队列中的所有等待任务删除。

    注意:
     AsyncTask不会不考虑结果而直接结束一个线程。调用cancel()其实是给AsyncTask设置一个"canceled"状态。这取决于你去检查AsyncTask是否已经取消,之后决定是否终止你的操作。对于mayInterruptIfRunning——它所作的只是向运行中的线程发出interrupt()调用。在这种情况下,你的线程是不可中断的,也就不会终止该线程。
     可以使用isCancelled()判断任务是否被取消,然后做相应的操作。

    参考文献:

    http://blog.csdn.net/pi9nc/article/details/12622797
    https://developer.android.google.cn/reference/android/os/AsyncTask.html#cancel(boolean)

    相关文章

      网友评论

          本文标题:AsyncTask使用总结及源码分析

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