这个其实现在已经不怎么用了,而且本身原理不复杂,就简单说一下吧。
老规矩先贴一个调用的代码,然后根据大流程来分析。

Step1、示例代码

public class AsyncTaskTestActivity extends DefaultActivity {

    private static final String TAG = "async_task";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test();
            }
        });
    }


    private void test() {
        //串行
        new MyAsyncTask().execute();
        new MyAsyncTask().execute();
        new MyAsyncTask().execute();
        
        //并行
        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    class MyAsyncTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            getTextView().setText("onPreExecute");
            getTextView().requestLayout();
            Log.d(TAG, "onPreExecute: " + Thread.currentThread().toString());
        }

        @Override
        protected Integer doInBackground(Integer... integers) {

            int i = 0;
            while (i < 10) {
                try {
                    Log.d(TAG, "doInBackground: " + Thread.currentThread().toString());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                publishProgress(i);
            }

            return i;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            getTextView().setText("onPostExecute: " + integer);
            getTextView().requestLayout();
            Log.d(TAG, "onPostExecute: " + Thread.currentThread().toString());
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            getTextView().setText("progress: " + values[0]);
        }
    }
}

代码很简单,就是点击button启动执行一个自定义的AsyncTask,注意这里既可以支持串行,又可以支持并行。
先看AsyncTask的构造函数:

Step2、创建任务

public AsyncTask() {
    this((Looper) null);
}

public AsyncTask(@Nullable Handler handler) {
    this(handler != null ? handler.getLooper() : null);
}

public AsyncTask(@Nullable Looper callbackLooper) {
	//正常情况callbackLooper一定为空,所以mHandler一定是调用getMainHander()返回的结果
    mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
        ? getMainHandler()
        : new Handler(callbackLooper);

    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;
        }
    };
	//不太懂的同学可以去看下Java的,Callable和FutureTask,这里明确的就是最终调用时,会先调用Callable的call方法,完成后可以从FutureTask的done方法里通过get拿到result
    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 occurred while executing doInBackground()",
                        e.getCause());
            } catch (CancellationException e) {
                postResultIfNotInvoked(null);
            }
        }
    };
}

实际正常情况下我们只能用第一个,那两个都是hide,细节参考注释。
构造函数跑完时候并没有任何任务开始执行,都只是设置回调而已。那执行任务一定是在execute方法里了。

Step3、串行,execute(),并行,executeOnExecutor()

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor, params);
}
//最终都调用这个方法,只是串行使用了默认的队列Executor
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方法,注意这个方法并没有用handler处理,所以如果是在子线程中回调且操作界面,是会崩溃的,算是个设计缺陷吧
    onPreExecute();

    mWorker.mParams = params;
    //真正跑任务的方法,分析见下文
    exec.execute(mFuture);

    return this;
}

下面看下sDefaultExecutor:

private static volatile Executor 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;
	
	//上文中的exec.execute(mFuture);就是调用的这里,在deque中放入了一个Runnable,最终线程池在执行的时候,会回调mFuture的run方法 -> Callable的call方法->FutureTask的done方法,执行完成才会去执行下一个任务
    public synchronized void execute(final Runnable r) {
        mTasks.offer(new Runnable() {
            public void run() {
                try {
                    r.run();
                } finally {
                    scheduleNext();
                }
            }
        });
        //第一次mActive一定为null,走到这里
        if (mActive == null) {
            scheduleNext();
        }
    }

	//从队列中取出一个task然后执行
    protected synchronized void scheduleNext() {
        if ((mActive = mTasks.poll()) != null) {
            THREAD_POOL_EXECUTOR.execute(mActive);
        }
    }
}
//就是个java线程池
public static final Executor THREAD_POOL_EXECUTOR;

static {
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), sThreadFactory);
    threadPoolExecutor.setRejectedExecutionHandler(sRunOnSerialPolicy);
    THREAD_POOL_EXECUTOR = threadPoolExecutor;
}

好,线程开始执行后我们回看下前面的mWorker和mFuture:

mWorker = new WorkerRunnable<Params, Result>() {
    public Result call() throws Exception {
        //标识任务被invoke
        mTaskInvoked.set(true);
        Result result = null;
        try {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //回调我们的doInBackground方法
            result = doInBackground(mParams);
            Binder.flushPendingCommands();
        } catch (Throwable tr) {
        	//发生异常时设置标记位
            mCancelled.set(true);
            throw tr;
        } finally {
        	//提交结果
            postResult(result);
        }
        return result;
    }
};

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

//最终都会走到postResult方法
private void postResultIfNotInvoked(Result result) {
    final boolean wasTaskInvoked = mTaskInvoked.get();
    if (!wasTaskInvoked) {
        postResult(result);
    }
}

Step4、postResult

private Result postResult(Result result) {
    @SuppressWarnings("unchecked")
    //这里的handler就是构造函数赋值的handler
    Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
            new AsyncTaskResult<Result>(this, result));
    message.sendToTarget();
    return result;
}

private Handler getHandler() {
    return mHandler;
}

mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

private static Handler getMainHandler() {
    synchronized (AsyncTask.class) {
        if (sHandler == null) {
            sHandler = new InternalHandler(Looper.getMainLooper());
        }
        return sHandler;
    }
}

好,最后看下这个InternalHandler。

private static class InternalHandler extends Handler {
    public InternalHandler(Looper looper) {
        super(looper);
    }

    @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);
    } else {
        onPostExecute(result);
    }
    mStatus = Status.FINISHED;
}

OK,这样就串起来了,postResult的时候会给这个handler发消息,收到消息后调用task的finish方法,这里会回调最终的onCancelled或者onPostExecute方法。

Step Extra、更新进度

protected final void publishProgress(Progress... values) {
    if (!isCancelled()) {
        getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                new AsyncTaskResult<Progress>(this, values)).sendToTarget();
    }
}

恩,就是发个消息给handler更新进度而已,so easy。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐