AsyncTask

作者: sollian | 来源:发表于2018-07-03 18:19 被阅读5次

    基于android api27源码。

    开始

    AsyncTask将在异步线程进行计算,然后主线程发布结果进行了包装,免去了手动操作Thread和Handler类。
    AsyncTask应该尽量用来计算耗时较短的操作(最多几秒钟)。如果你需要进行长时间的异步运算,推荐使用线程池技术。

    下面是使用AsyncTask的一个例子:

     private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls) {
             int count = urls.length;
             long totalSize = 0;
             for (int i = 0; i < count; i++) {
                 totalSize += Downloader.downloadFile(urls[i]);
                 //发布进度
                 publishProgress((int) ((i / (float) count) * 100));
                 // Escape early if cancel() is called
                 if (isCancelled()) break;
             }
             return totalSize;
         }
    
         protected void onProgressUpdate(Integer... progress) {
             setProgressPercent(progress[0]);
         }
    
         protected void onPostExecute(Long result) {
             showDialog("Downloaded " + result + " bytes");
         }
     }
    

    然后如下调用:

     new DownloadFilesTask().execute(url1, url2, url3);
    

    AsyncTask的三个泛型参数如下:

    1. Params:需要传递的参数。
    2. Progress:进度的类型。
    3. Result:运算结果的类型。

    如果某个参数不需要,可以使用Void

    AsyncTask的运行步骤

    1. onPreExecute():UI线程执行,表示异步任务即将开始。该方法通常用来设置任务,比如展示一个进度条。
    2. doInBackground(Params ...):异步线程执行,在onPreExecute()之后执行。该方法执行具体的异步运算,运算结果传递给最后一步。该方法也可以通过调用publishProgress(Progress ...)方法来向UI线程发布进度。
    3. onProgressUpdate(Progress ...):接收publishProgress(Progress ...)方法发布的进度。可以通过该方法更新进度条。
    4. onPostExecute(Result):UI线程执行,接收异步运算的结果。

    取消任务

    可以在任意时间通过调用cancel(boolean)方法取消任务。
    调用该方法后,isCancelled()方法会返回true。并且doInBackground(Object[])运行完毕后,会执行onCancelled(Object)而非onPostExecute(Object)
    为了保证尽快取消任务,需要尽可能多的检查isCancelled()方法是不是返回true

    线程规则

    为了保证AsyncTask正常运行,需要遵循如下规则:

    1. AsyncTask类必须在UI线程加载。
    2. AsyncTask实例必须在UI线程创建。
    3. execute(Params ...)方法必须在UI线程调用。
    4. 不要手动调用onPreExecute()onPostExecute(Result)doInBackground(Params ...)onProgressUpdate(Progress ...)
    5. 每个任务只能执行一次,第二次执行会抛出异常。

    执行顺序

    AsyncTask刚出现时,通过一个单一的异步线程串行执行;
    api4开始,使用了线程池,可以并行运行;
    api11开始,通过单一线程串行执行。

    如果确实想要并行运行,可以调用executeOnExecutor(Executor, Object[]方法。


    静态变量

    介绍两个公有静态常量,外部程序可以使用。

    SERIAL_EXECUTOR

        /**
         * An {@link Executor} that executes tasks one at a time in serial
         * order.  This serialization is global to a particular process.
         */
        public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    

    SERIAL_EXECUTOR是AsyncTask默认的异步任务执行者。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() {
                        try {
                            r.run();
                        } finally {
                            scheduleNext();
                        }
                    }
                });
                if (mActive == null) {
                    scheduleNext();
                }
            }
    
            protected synchronized void scheduleNext() {
                if ((mActive = mTasks.poll()) != null) {
                    THREAD_POOL_EXECUTOR.execute(mActive);
                }
            }
        }
    

    由源码可知,SerialExecutor最终将任务交由THREAD_POOL_EXECUTOR执行。

    THREAD_POOL_EXECUTOR

        public static final Executor THREAD_POOL_EXECUTOR;
    
        static {
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                    sPoolWorkQueue, sThreadFactory);
            threadPoolExecutor.allowCoreThreadTimeOut(true);
            THREAD_POOL_EXECUTOR = threadPoolExecutor;
        }
    

    THREAD_POOL_EXECUTOR是一个自定义了参数的线程池,各个参数如下:

        private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
        // We want at least 2 threads and at most 4 threads in the core pool,
        // preferring to have 1 less than the CPU count to avoid saturating
        // the CPU with background work
        private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
        private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
        private static final int KEEP_ALIVE_SECONDS = 30;
    
        private static final ThreadFactory sThreadFactory = new ThreadFactory() {
            private final AtomicInteger mCount = new AtomicInteger(1);
    
            public Thread newThread(Runnable r) {
                return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
            }
        };
    
        private static final BlockingQueue<Runnable> sPoolWorkQueue =
                new LinkedBlockingQueue<Runnable>(128);
    

    状态

        /**
         * 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,//结束
        }
    

    指示当前任务的状态,每个状态只能设置一次。

    AsyncTask中的状态变量定义如下:

        private volatile Status mStatus = Status.PENDING;
    

    volatile变量,初始值为Status.PENDING

        public final Status getStatus() {
            return mStatus;
        }
    

    该方法获取当前任务的状态。

    构造方法

    在看构造方法之前,先看几个变量:

        private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
        //默认的向主线程发送消息的handler
        private static InternalHandler sHandler;
    
        private final WorkerRunnable<Params, Result> mWorker;
        private final FutureTask<Result> mFuture;
        
        //当前任务是否被取消
        private final AtomicBoolean mCancelled = new AtomicBoolean();
        //当前任务是否被执行
        private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
    
        //当前异步任务使用的handler
        private final Handler mHandler;
    

    InternalHandler是一个静态内部类:

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

    该类用来将异步线程的进度和结果发送到主线程。

    finish方法如下:

        private void finish(Result result) {
            if (isCancelled()) {
                onCancelled(result);
            } else {
                onPostExecute(result);
            }
            //状态置为结束态
            mStatus = Status.FINISHED;
        }
    

    AsyncTaskResult也是一个静态内部类:

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

    该类用来传递异步任务的进度和结果。

    WorkerRunnable是一个静态内部抽象类:

        private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
            //用来传递参数
            Params[] mParams;
        }
    

    有如下三个构造方法,但只有第一个是外部可用的,其他两个都有@hide注解:

        /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            this((Looper) null);
        }
    
        /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         *
         * @hide
         */
        public AsyncTask(@Nullable Handler handler) {
            this(handler != null ? handler.getLooper() : null);
        }
    
        /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         *
         * @hide
         */
        public AsyncTask(@Nullable Looper callbackLooper) {
            mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
                ? getMainHandler()//返回默认的向UI线程发送消息的sHandler
                : new Handler(callbackLooper);
    
            mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);//任务执行标记设为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;
                }
            };
    
            //将Callable包装成FutureTask,以便Executor执行。
            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);
                    }
                }
            };
        }
    
        //任务未被调用时,发布结果
        private void postResultIfNotInvoked(Result result) {
            final boolean wasTaskInvoked = mTaskInvoked.get();
            if (!wasTaskInvoked) {
                postResult(result);
            }
        }
    

    postResult(Result)方法负责向mHandler发送带有运算结果的消息。

    可覆写的protected方法

        @MainThread
        protected void onPreExecute() {
        }
    
        @MainThread
        protected void onPostExecute(Result result) {
        }
    
        @MainThread
        protected void onProgressUpdate(Progress... values) {
        }
    
        @MainThread
        protected void onCancelled(Result result) {
            onCancelled();
        }  
    
        @MainThread
        protected void onCancelled() {
        }
    

    其他方法

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

    用来发布进度

        public final boolean cancel(boolean mayInterruptIfRunning) {
            mCancelled.set(true);
            return mFuture.cancel(mayInterruptIfRunning);
        }
    

    尝试取消任务。若任务已经结束,或者无法取消,则返回false。

        public final boolean isCancelled() {
            return mCancelled.get();
        }
    

    判断任务是否已取消。

        public final Result get() throws InterruptedException, ExecutionException {
            return mFuture.get();
        }
    
        public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
                ExecutionException, TimeoutException {
            return mFuture.get(timeout, unit);
        }
    

    阻塞方法,获取执行结果。

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

    执行任务。

        @MainThread
        public static void execute(Runnable runnable) {
            sDefaultExecutor.execute(runnable);
        }
    

    静态方法,使用AsyncTask的默认的Executor执行任务,注意是串行执行。

    相关文章

      网友评论

          本文标题:AsyncTask

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