网友通过本文主要向大家介绍了asynctask源码,asynctask源码分析,asynctask,asynctask的使用,android asynctask等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
AsyncTask源码探究,asynctask源码
整天用AsyncTask,但它的内部原理一直没有特意去研究,今天趁着有时间,码下它的原理。
具体用法就不再说明,相信大家已经用得很熟练了,我们今天就从它怎么运行开始说。先新建好我们的AsyncTask:
1 class MyAsyncTask extends AsyncTask<String,Integer,Boolean>{ 2 3 @Override 4 protected Boolean doInBackground(String... voids) { 5 return true; 6 } 7 }
好了,一个最基本的代码已经好了,接下来我们怎么运行它呢?当然,大家都知道的。
new MyAsyncTask().execute("参数");
那平时做到这里,我们可能已经不去往不管了,因为已经执行起来了,但是,你有没有想过
- 为什么调用execute()就可以运行了
- 为什么doInBackground()方法里面不能操作UI,而onPostExecute就可以
等等一连串的问题,接下来,我们就一步一步的去看一下,它内部到底做了哪些。
首先,我们看到它new了一个AsyncTask对象,那我们就去它构建函数看看。
1 public AsyncTask() { 2 mWorker = new WorkerRunnable<Params, Result>() { 3 public Result call() throws Exception { 4 mTaskInvoked.set(true); 5 6 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 7 //noinspection unchecked 8 Result result = doInBackground(mParams); 9 Binder.flushPendingCommands(); 10 return postResult(result); 11 } 12 }; 13 14 mFuture = new FutureTask<Result>(mWorker) { 15 @Override 16 protected void done() { 17 try { 18 postResultIfNotInvoked(get()); 19 } catch (InterruptedException e) { 20 android.util.Log.w(LOG_TAG, e); 21 } catch (ExecutionException e) { 22 throw new RuntimeException("An error occurred while executing doInBackground()", 23 e.getCause()); 24 } catch (CancellationException e) { 25 postResultIfNotInvoked(null); 26 } 27 } 28 }; 29 }
看着很多,其它就是new了两个对象mWorker和mFuture,其实它们分别是Callable和Future的实现,关于它们两个的实现原理,我会在另外一篇文章里讲解。需要注意的是,在实例化mFuture时,把mWorker当作参数传入。现在还没有用到它们,我们接下来往下看execute():
1 @MainThread 2 public final AsyncTask<Params, Progress, Result> execute(Params... params) { 3 return executeOnExecutor(sDefaultExecutor, params); 4 } 5 6 @MainThread 7 public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, 8 Params... params) { 9 if (mStatus != Status.PENDING) { 10 switch (mStatus) { 11 case RUNNING: 12 throw new IllegalStateException("Cannot execute task:" 13 + " the task is already running."); 14 case FINISHED: 15 throw new IllegalStateException("Cannot execute task:" 16 + " the task has already been executed " 17 + "(a task can be executed only once)"); 18 } 19 } 20 21 mStatus = Status.RUNNING; 22 23 onPreExecute(); 24 25 mWorker.mParams = params; 26 exec.execute(mFuture); 27 28 return this; 29 }
我们看到了onPreExecute(),这也解释了它确实比doInBackground运行的早,可以做一些准备工作。接下来,用到了我们前面提到的两个对象,这里是把我们传递过去的参数赋给了mWorker的变量,然后看26行 调用了Executor的execute(),并且把mFuture做为参数传递过去了,那我们看上一个方法,是把sDefaultExecutor当作参数传递过来的,那就看下它的定义:
1 public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); 2 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
它的最后实现类是SerialExecutor。我们接着看这个类定义了什么。
1 private static class SerialExecutor implements Executor { 2 final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); 3 Runnable mActive; 4 5 public synchronized void execute(final Runnable r) { 6 mTasks.offer(new Runnable() { 7 public void run() { 8 try { 9 r.run(); 10 } finally { 11 scheduleNext(); 12 } 13 } 14 }); 15 if (mActive == null) { 16 scheduleNext(); 17 } 18 } 19 20 protected synchronized void scheduleNext() { 21 if ((mActive = mTasks.poll()) != null) { 22 THREAD_POOL_EXECUTOR.execute(mActive); 23 } 24 }