android 源码探索--AsyncTask

来源:互联网 发布:java qq登录界面 编辑:程序博客网 时间:2024/05/21 09:28

本文是个人学习AsyncTask时整理的一些东西|白龙出品,支持原创|  转载请注明出处:http://blog.csdn.net/bailong025/article/details/42360341

首先android刷新ui的线程是单线程的,不能在里面处理一些耗时的操作,否则会造成程序未响应而出现anr(Application Not Responding)异常,即使不出现异常也会导致界面卡顿,影响用户体验。

AsyncTask是android提供的可以异步操作线程的类,内部原理为线程+handler,所以AsyncTask对外开放了几个方法可以用来刷新ui,他们是


protected void onPreExecute();protected void onPostExecute(Result result);protected void onProgressUpdate(Progress... values) ;protected void onCancelled(Result result);

以及一个必须实现的执行耗时操作的方法

protected abstract Result doInBackground(Params... params);

首先来看下AsyncTask中的一些参数

private static final String LOG_TAG = "AsyncTask";private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();/** 可以同时执行的核心线程个数 **/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 ThreadFactory sThreadFactory = new ThreadFactory() {private final AtomicInteger mCount = new AtomicInteger(1);public Thread newThread(Runnable r) {return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());}};/** 装载等待线程的队列,最多存放128个(当工作线程满时被放入等待队列) **/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);/** * 这个线程池没有真正的去运行提交到里面的Runnable,只是顺序的存入队列又取出来, * 将Runnable提交到了THREAD_POOL_EXECUTOR线程池 */public static final Executor SERIAL_EXECUTOR = new SerialExecutor();private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;/** 消息类型--提交结果 **/private static final int MESSAGE_POST_RESULT = 0x1;/** 消息类型--刷新进度 **/private static final int MESSAGE_POST_PROGRESS = 0x2;/** AsyncTask内部处理刷新ui的handler **/private static final InternalHandler sHandler = new InternalHandler();/** * 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,}


现在我们看到了AsyncTask内部其实用的是线城池

然后看一下当我们调用execute时做了什么

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方法,这时如果我们重写了这个方法就会执行,由于AsyncTask是在ui线程执行的execute, * 所以在onPreExecute()中可以刷新我们的ui **/onPreExecute();/** 修改WorkerRunnable中的参数为本次传入的 **/mWorker.mParams = params;/** 提交修改后的异步任务到转发线程池 **/exec.execute(mFuture);return this;}


 

上面在调用onPreExecute()方法后执行了

exec.execute(mFuture);

将修改后的异步任务提交到转发线程池,下面是转发线程池的代码

private static class SerialExecutor implements Executor {final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();Runnable mActive;public synchronized void execute(final Runnable r) {/** 向mTasks队列中压入Runnable **/mTasks.offer(new Runnable() {public void run() {try {r.run();} finally {scheduleNext();}}});if (mActive == null) {scheduleNext();}}protected synchronized void scheduleNext() {/** 从队列里取出Runnable,提交到THREAD_POOL_EXECUTOR线程池 **/if ((mActive = mTasks.poll()) != null) {THREAD_POOL_EXECUTOR.execute(mActive);}}}



下面再看看FutureTask做了什么

 /**     * 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,调用doInBackground放法并将返回值传给postResult方法                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);                }            }        };    }
 private void postResultIfNotInvoked(Result result) {        final boolean wasTaskInvoked = mTaskInvoked.get();        if (!wasTaskInvoked) {            postResult(result);        }    }    private Result postResult(Result result) {        @SuppressWarnings("unchecked")        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,                new AsyncTaskResult<Result>(this, result));        message.sendToTarget();        return result;    }
 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {        Params[] mParams;    }

WorkerRunnable的实质是实现了Callable接口,当执行了Callable的call()方法,然后会执行FutureTask中的done()方法,这时在FutureTask通过调用get()发法可以得到call()方法的返回值。然后调用了postResult(Result result)将结果提交到handler中。然后看一下handler中做了什么


 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;            }        }    }
 private void finish(Result result) {        if (isCancelled()) {              onCancelled(result);//如果任务被取消,可以在onCancelled(result)中收到,由于是在handler中调用的所以可以刷新ui        } else {             onPostExecute(result);//如果任务没有被取消,执行onPostExecute(result),同样可以刷新ui        }        mStatus = Status.FINISHED;//改变AsyncTask状态    }
 private static class AsyncTaskResult<Data> {        final AsyncTask mTask;        final Data[] mData;
//AsyncTaskResult中仅仅是封装了AsyncTask和一个参数。        AsyncTaskResult(AsyncTask task, Data... data) {            mTask = task;            mData = data;        }    }

至此AsyncTask的流程结束。



0 0
原创粉丝点击