第八章 AsyncTask

一、什么是AsyncTask

AsyncTask是轻量级的用于处理简单的异步任务,不需要借助线程和Handler即可实现。除了之外还有以下方法解决线程不能更新UI组件问题;

  • 使用Handler实现线程间通讯
  • Activity.runOnUIThread(Runnable);
  • View.post(Runnable)
  • View.postDelayed(Runnable);

二、AsyncTask的使用方法

1.创建AsyncTask的子类,并为三个泛型指定类型的参数,如果不需要制定则Void.
2.根据需要调用onPreExecute(),onPostExecute(Void aVoid),doInBackground(Void... voids),onProgressUpdate(Void... values) 等方法
3.调用AsyncTask子类的execute(Param params)执行耗时任务

  PAsyncTask pAsyncTask=new PAsyncTask();
  pAsyncTask.execute("广州");


    private class PAsyncTask extends AsyncTask{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected String doInBackground(String... strings) {
            return null;
        }
    }

四、AsyncTask机制原理

  /**
     * 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()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable() {
            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(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);
                }
            }
        };
    }

此处是AsyncTask的构造方法,创建了WorkerRunnable、FutureTask 的实例mWorker和mFuture,其中mWorker实现了call()的接口,处理doInBackground()数据,mFuture则是实现了Runnable接口的子线程,里面调用了mWorker的call()接口

 public final AsyncTask 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;
    }

这里先是在UI线程中执行了onPreExecute(); exec.execute(mFuture);方法中exec是实现了Executor接口的(如下), r.run();是实现了Runable接口的mFuture子线程,具体执行子线程实在线程队列mTasks 中执行。

  private static class SerialExecutor implements Executor {
        final ArrayDeque mTasks = new ArrayDeque();
        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);
            }
        }
    }

而后在postResult()方法中使用Handler发送消息通知UI线程

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

总结:

  • AsyncTask使用了FutureTask和Handler的结合,其中FutureTask实现了runnable接口,SerialExecutor则采用线程池的方式管理线程。
  • AsyncTask在代码上比Handler要轻量级别,但实际上比Handler更耗资源,因为AsyncTask底层是一个线程池,而Handler仅仅就是发送了一个消息队列。但是,如果异步任务的数据特别庞大,AsyncTask线程池比Handler节省开销,因为Handler需要不停的new Thread执行。
  • AsyncTask的实例化只能在主线程,Handler可以随意,只和Looper有关系,因此为什么开发中比较少用AsyncTask,而Handler+Runnable的方式更加灵活多变来适应不同的业务需求。

五、AsyncTask注意事项

  • 必须在UI线程中创建AsyncTask的实例
  • 在UI线程中调用AsyncTask的execute();
  • AsyncTask只能被执行一次,多次调用会引发异常

你可能感兴趣的:(第八章 AsyncTask)