Android异步任务之AsyncTask源码解析

AsyncTask是一个抽象类:

public abstract class AsyncTask<Params, Progress, Result> {
    ......
}
我们要使用AsyncTask时需要写重新写一个类继承 AsyncTask,然后调用其execute方法即可:

MyAsyncTask myAsyncTask = new MyAsyncTask(progressBar,textView);
myAsyncTask.execute(10);
现在开始从 execute分析起:

/**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>Note: this function schedules the task on a queue for a single background
     * thread or pool of threads depending on the platform version.  When first
     * introduced, AsyncTasks were executed serially on a single background thread.
     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
     * to a pool of threads allowing multiple tasks to operate in parallel. Starting
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
     * executed on a single thread to avoid common application errors caused
     * by parallel execution.  If you truly want parallel execution, you can use
     * the {@link #executeOnExecutor} version of this method
     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
     * on its use.
     *
     * <p>This method must be invoked on the UI thread.   //这个方法必须在UI线程中调用
     *
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     * @see #execute(Runnable)
     */
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

在execute方法中传入需要的参数,即对应三个泛型参数中的Params。
在execute中,调用executeOnExecutor方法,参数sDefaultExecutor为SerialExecute的一个实例:
private static volatile Executor sDefaultExecutor = 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();
而SerialExecutor为AsyncTask的一个静态内部类,实现Execute:
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() {    //offer:将元素插入此双端列表的尾端 
                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);
            }
        }
    }
再看 executeOnExecutor方法:

/**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
     * allow multiple tasks to run in parallel on a pool of threads managed by
     * AsyncTask, however you can also use your own {@link Executor} for custom
     * behavior.
     * 
     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
     * a thread pool is generally <em>not</em> what one wants, because the order
     * of their operation is not defined.  For example, if these tasks are used
     * to modify any state in common (such as writing a file due to a button click),
     * there are no guarantees on the order of the modifications.
     * Without careful work it is possible in rare cases for the newer version
     * of the data to be over-written by an older one, leading to obscure data
     * loss and stability issues.  Such changes are best
     * executed in serial; to guarantee such work is serialized regardless of
     * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
     *              convenient process-wide thread pool for tasks that are loosely coupled.
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #execute(Object[])
     */
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {  //state为RUNNING或是FINISH的时候再次调用ececute会报异常
            switch (mStatus) {            //也就是一个Task只能被执行一次,多次调用会出现异常
                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;   //设置状态为RUNNING
        onPreExecute();     //在UI线程中执行,在doInBackground函数之前被调用,具体事务由用户实现
       //mWorker为WorkerRunnable<Params,Result>的实例,WorkerRunnable实现Callable<V>
        mWorker.mParams = params;   
        exec.execute(mFuture);  //mFuture为:FutureTask<Result>
        return this;
    }
先看mWorker:

private final WorkerRunnable<Params, Result> mWorker;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
}
再看mFuture:

private final FutureTask<Result> mFuture; //FutureTask可以包装Callable和Runnable对象,进行异步任务
mWorker和 mFuture的 其初始化在AsyncTask的构造函数中:

 /**
     * 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);
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };
        mFuture = new FutureTask<Result>(mWorker) {     //执行指定的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);
                }
            }
        };
    }

再看exec.execute(mFuture):
此时exec为sDefaultExecutor,执行其 execute函数:
public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {       //把Runnable对象插入到队列中
                public void run() {
                    try {
                        r.run();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {//一开始执行的时候,mActive为null,满足条件,执行scheduleNext函数
                scheduleNext();
            }
        }
其中scheduleNext方法为:
protected synchronized void scheduleNext() {
    if ((mActive = mTasks.poll()) != null) {  //获取队列中的元素,即添加进去的Runnable实例
         THREAD_POOL_EXECUTOR.execute(mActive); //THREAD_POOL_ECECUTE为ThreadPoolExecute对象,执行execute,线程池中会新建                                                  //或是使用一个已有的线程来进行处理mActive(即Runnable对象)
    }
}
其中THREAD_POOL_EXECUTE为:
 /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
其中sThreadFactory和sPoolWorkQueue分别为:
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);
在这里实际执行的是 WorkerRunnable中的call()方法:

public Result call() throws Exception {
                mTaskInvoked.set(true);
                //设置线程优先级为10,一般的优先级为0,10低于0
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams)); //开始执行doInBackground方法,其实是在一个优先级比较低的线程中执行。
            }

doInBackground方法由用户自己重写。
postResult方法把结果返回,为:
private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }
其中sHandler为:
private static final InternalHandler sHandler = new InternalHandler();
private static class InternalHandler extends Handler {
        @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);       //执行onPostExecute,由用户实现
        }
        mStatus = Status.FINISHED;       //改变状态
    }
其中 AsyncTaskR esult, 这个只是在 AsyncTask中进行数据传递, 为:

private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;
        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
一般我们也会实现onProgressUpdate来更新显示数据,在 InternalHandler处理数据的时候用到:

//在执行任务的过程中更新显示数据,UI线程的publishProgress执行之后调用此方法
	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
		int value = values[0];
		progressBar.setProgress(value+1);
	}
case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
其中消息MESSAGE_POST_PROGRESS是在publishProgress函数中发出:

/**
     * This method can be invoked from {@link #doInBackground} to
     * publish updates on the UI thread while the background computation is
     * still running. Each call to this method will trigger the execution of
     * {@link #onProgressUpdate} on the UI thread.
     *
     * {@link #onProgressUpdate} will note be called if the task has been
     * canceled.
     *
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }
所以我们一般会在doInBackground方法中调用publishProgress方法来更新显示进度条。

//后台执行任务,参数是在execute方法中传递进来,onPreExecute方法执行后执行此方法
	@Override
	protected String doInBackground(Integer... arg0) {
		// TODO Auto-generated method stub
		int value = arg0[0];
		Log.d("zmq","doInBackground value = "+value);
		for (int i = 0; i < value; i++) {
			operate.operate();
			publishProgress(i);
		}
		return "任务结束啦";
	}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值