Android知识Android开发Java学习笔记

Android:AsyncTask源码解读

2016-11-29  本文已影响102人  辣公公

标题党

AsyncTask源码解读,解读这么流弊的标题,吓得我都不敢写下去啦!菜鸟一枚,写不对的地方,请各位大神在留下评论或拍砖,我会为大家贡献更多多的妹子图。


妹子镇楼

PS妹子图镇楼,可以增加阅读量

AsyncTask简单使用

  1. 直接上代码,很简单就是在子线程中结算1到100的和。妹子你走开,我要开始撸代码啦!
public static void main(String arg[]) throws InterruptedException {
        MyTask task = new MyTask();
        task.execute(100);
    }
 static class MyTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            System.out.println("onPreExecute");
            super.onPreExecute();
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            System.out.println("onProgressUpdate " + values[0]);
            super.onProgressUpdate(values);
        }
        @Override
        protected Integer doInBackground(Integer... integers) {
            //在新的线程中执行
            int sum = 0;
            for (int i = 0; i < integers[0]; i++) {
                sum = sum + i;
                publishProgress(i);//给InternalHandler发送进度更新的消息
            }
            return sum;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            //将子线程的结果post到主线程
            super.onPostExecute(integer);
        }
    }
  1. 稍微介绍重要的几个方法;暂时忘记到妹子图吧!看看以下四个方法:@MainThread表示在主线程中执行,而@WorkerThread表示在子线程中执行
@MainThread
protected void onPreExecute() 
@MainThread
protected void onPostExecute(Result result) 
@MainThread
protected void onProgressUpdate(Progress... values)
@WorkerThread
protected abstract Result doInBackground(Params... params)

内部实现

上面讲了那么多,然而都不是重点,现在才刚开始进入主题。AsyncTask其实就是用线程池和和handle实现的!

  1. AsyncTask的三个状态
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,
    }
  1. 子线程与主线程通讯:(handle)
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]);//调用onPostExecute 将结果post到主线程
                    break;
                case MESSAGE_POST_PROGRESS://调用onProgressUpdate更新进度 
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }
private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }
  1. 构造函数
public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                Result result = doInBackground(mParams);//调用doInBackground 在子线程中做一系列的事情
                Binder.flushPendingCommands();
                return postResult(result);//给InternalHandler发送一个doInBackground任务执行完成的消息
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());//等待mWorker的call方法执行完成
                } 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);//如果doInBackground发生异常,则向主线程发送一个null的结果
                }
            }
        };
    }
  1. execute(params)最终调用executeOnExecutor
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();//在主线程总调用onPreExecute
       mWorker.mParams = params;//mWorker 设置参数
       exec.execute(mFuture);//线程池执行futureTask
       return this;
   }
  1. AsyncTask执行一个task的流程图
流程图1 流程图2 流程图3 流程图4
上一篇 下一篇

猜你喜欢

热点阅读