码迷,mamicode.com
首页 > 移动开发 > 详细

Android:AsyncTask源码解析

时间:2015-08-19 13:35:03      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:asynctask   源码   

简例

private class MyAsyncTask extends AsyncTask<String,Void,String>{

    @Override
    protected String doInBackground(String... params) {
        String str = params[0];
        return "disposed " + str;
    }

    @Override
    protected void onPostExecute(String s) {
        Log.e("TAG", s);
        super.onPostExecute(s);
    }
}
new MyAsyncTask().execute("leelit");

内部逻辑

1、实例化AsyncTask,new MyAsyncTask();

public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };

        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 occured while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

构造函数里面实例化两个对象,mWorker对象实现了Callable< result>,mFuture在这里可以看作是对mWorker的一次包装,他是一个FutureTask对象。

2、myAsyncTask.execute(params)

    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, 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;
    }
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

execute方法直接调用executeOnExecutor方法,在这个方法内部:

  • 首先进行状态的判断和设置,这里也说明一个AsyncTask对象只能execute一次,否则抛出异常;
  • 然后执行一个onPreExecute()方法,这也是我们可以重写的执行流程的第一个执行方法;
  • 设置mWorker参数;
  • 线程池执行任务。

注意,这里的exec传递进来的是sDefaultExecutor,而sDefaultExecutor = SERIAL_EXECUTOR,从名字就可以看出他是串行执行任务的,接着看下去。

public static final Executor SERIAL_EXECUTOR = new 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);
            }
        }
    }

上面这段代码还是比较好明白的,就是串行执行任务的实现。里面的线程池THREAD_POOL_EXECUTOR,各个版本也会有所不同,不过大多数任务队列都设在了128。

    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);  

    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

执行全过程

1、实例化MyAsyncTask对象,实例化mWorker对象和mFuture对象。
2、调用execute方法,判断设置状态,执行可选择重写的onPreExecute();方法,设置参数,内部线程池执行任务,exec.execute(mFuture)。
3、执行mWorker里面的任务,调用doInBackground(mParams)方法,这也是必须重写的,
4、执行postResult方法,将消息发回主线程,postResult(doInBackground(mParams));

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

5、Handler处理消息,这里辗转到最后就会调用重写的需要在主线程处理的 onPostExecute(result);方法

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

另外一个常用的方法是publishProgress,它也是通过Handler发送一个消息给主线程去处理

getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();

小结

1、每个AsyncTask对象只能执行一次任务,因为其内部会有状态判断和设置;
2、内部共用一个线程池,任务队列为128,串行顺序执行任务,不过最后效果还是会看具体的线程池。
3、实例化AsyncTask对象,构造函数就是实例化一个 FutureTask对象,一旦运行就执行给定的 Callable。 这里的Callable对象就是mWorker,其内部是执行doInBackground(mParams)方法,这也是必须重写的,最后执行postResult方法,通过Handler将消息发回主线程,postResult(doInBackground(mParams))。

实例化AsyncTask对象,就是实例化任务对象,这个任务内部调用重写的方法;
调用执行方法就是线程池去执行任务,最后通过Handler来完成异步通信。

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android:AsyncTask源码解析

标签:asynctask   源码   

原文地址:http://blog.csdn.net/leelit/article/details/47777655

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!