/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ publicAsyncTask(){ this((Looper) null); }
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. * * @hide */ publicAsyncTask(@Nullable Handler handler){ this(handler != null ? handler.getLooper() : null); }
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. * * @hide */ publicAsyncTask(@Nullable Looper callbackLooper){ mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper() ? getMainHandler() : new Handler(callbackLooper); // 创建一个handler,实际是一个InternalHandler对象 /** private static Handler getMainHandler() { synchronized (AsyncTask.class) { if (sHandler == null) { sHandler = new InternalHandler(Looper.getMainLooper()); } return sHandler; } } **/
mWorker = new WorkerRunnable<Params, Result>() { public Result call()throws Exception { mTaskInvoked.set(true); Result result = null; try { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked result = doInBackground(mParams); Binder.flushPendingCommands(); } catch (Throwable tr) { mCancelled.set(true); throw tr; } finally { postResult(result); } return result; } }; /** // WorkerRunnable实现了Callable接口 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } // 这个接口与Runnable作用一样,只是Callable可以返回对象,以及抛出异常 public interface Callable<V> { V call() throws Exception; } **/
publicfinal AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params){ if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: thrownew IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: thrownew IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } }
publicvoidrun(){ if (state != NEW || !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread())) return; try { // 这里拿出之前初始化的workerRunnable。 Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result); // 把结果设置到outcome,然后再调用到done()接口。 } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }
protectedvoidset(V v){ if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) { outcome = v; U.putOrderedInt(this, STATE, NORMAL); // final state finishCompletion(); } }
privatevoidfinishCompletion(){ // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (U.compareAndSwapObject(this, WAITERS, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } }
/** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ @WorkerThread protectedabstract Result doInBackground(Params... params);
/** public V get() throws InterruptedException, ExecutionException { int s = state; if (s <= COMPLETING) s = awaitDone(false, 0L); return report(s); } // 返回outcome,否则抛出Exception private V report(int s) throws ExecutionException { Object x = outcome; if (s == NORMAL) return (V)x; if (s >= CANCELLED) throw new CancellationException(); throw new ExecutionException((Throwable)x); } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); // worker.call的时候设置为true if (!wasTaskInvoked) { // 如果worker.call的过程出现Exception,这里确保能够结束任务。 postResult(result); } } **/
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override publicvoidhandleMessage(Message msg){ AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result // 这个mTask是AsyncTask自身 result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: // 调用onProgressUpdate接口,这个接口也会抽象函数,由具体业务实现 result.mTask.onProgressUpdate(result.mData); break; } } }