标题党
AsyncTask源码解读,解读这么流弊的标题,吓得我都不敢写下去啦!菜鸟一枚,写不对的地方,请各位大神在留下评论或拍砖,我会为大家贡献更多多的妹子图。
PS妹子图镇楼,可以增加阅读量
AsyncTask简单使用
- 直接上代码,很简单就是在子线程中结算1到100的和。妹子你走开,我要开始撸代码啦!
public static void main(String arg[]) throws InterruptedException {
MyTask task = new MyTask();
task.execute(100);
}
static class MyTask extends AsyncTask<Integer, Integer, Integer> {
@Override
protected void onPreExecute() {
System.out.println("onPreExecute");
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
System.out.println("onProgressUpdate " + values[0]);
super.onProgressUpdate(values);
}
@Override
protected Integer doInBackground(Integer... integers) {
//在新的线程中执行
int sum = 0;
for (int i = 0; i < integers[0]; i++) {
sum = sum + i;
publishProgress(i);//给InternalHandler发送进度更新的消息
}
return sum;
}
@Override
protected void onPostExecute(Integer integer) {
//将子线程的结果post到主线程
super.onPostExecute(integer);
}
}
- 稍微介绍重要的几个方法;暂时忘记到妹子图吧!看看以下四个方法:@MainThread表示在主线程中执行,而@WorkerThread表示在子线程中执行
@MainThread
protected void onPreExecute()
@MainThread
protected void onPostExecute(Result result)
@MainThread
protected void onProgressUpdate(Progress... values)
@WorkerThread
protected abstract Result doInBackground(Params... params)
onPreExecute:表示该方法是运行在主线程中的。在AsyncTask执行了execute()方法后就会在UI线程上执行onPreExecute()方法,该方法在task真正执行前运行,我们通常可以在该方法中显示一个进度条,从而告知用户后台任务即将开始。
doInBackground :表示该方法是运行在单独的工作线程中的,而不是运行在主线程中。doInBackground会在onPreExecute()方法执行完成后立即执行,该方法用于在工作线程中执行耗时任务,我们可以在该方法中编写我们需要在后台线程中运行的逻辑代码,由于是运行在工作线程中,所以该方法不会阻塞UI线程。该方法接收Params泛型参数,参数params是Params类型的不定长数组,该方法的返回值是Result泛型,由于doInBackgroud是抽象方法,我们在使用AsyncTask时必须重写该方法。在doInBackground中执行的任务可能要分解为好多步骤,每完成一步我们就可以通过调用AsyncTask的publishProgress(Progress…)将阶段性的处理结果发布出去,阶段性处理结果是Progress泛型类型。当调用了publishProgress方法后,处理结果会被传递到UI线程中,并在UI线程中回调onProgressUpdate方法,下面会详细介绍。根据我们的具体需要,我们可以在doInBackground中不调用publishProgress方法,当然也可以在该方法中多次调用publishProgress方法。doInBackgroud方法的返回值表示后台线程完成任务之后的结果。
onProgressUpdate 上面我们知道,当我们在doInBackground中调用publishProgress(Progress…)方法后,就会在UI线程上回调onProgressUpdate方法
注解,表示该方法是在主线程上被调用的,且传入的参数是Progress泛型定义的不定长数组。如果在doInBackground中多次调用了publishProgress方法,那么主线程就会多次回调onProgressUpdate方法。onPostExecute :表示该方法是在主线程中被调用的。当doInBackgroud方法执行完毕后,就表示任务完成了,doInBackgroud方法的返回值就会作为参数在主线程中传入到onPostExecute方法中,这样就可以在主线程中根据任务的执行结果更新UI。
内部实现
上面讲了那么多,然而都不是重点,现在才刚开始进入主题。AsyncTask其实就是用线程池和和handle实现的!
- 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,
}
- 子线程与主线程通讯:(handle)
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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]);//调用onPostExecute 将结果post到主线程
break;
case MESSAGE_POST_PROGRESS://调用onProgressUpdate更新进度
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
- 构造函数
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);//调用doInBackground 在子线程中做一系列的事情
Binder.flushPendingCommands();
return postResult(result);//给InternalHandler发送一个doInBackground任务执行完成的消息
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());//等待mWorker的call方法执行完成
} 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);//如果doInBackground发生异常,则向主线程发送一个null的结果
}
}
};
}
- execute(params)最终调用executeOnExecutor
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();//在主线程总调用onPreExecute
mWorker.mParams = params;//mWorker 设置参数
exec.execute(mFuture);//线程池执行futureTask
return this;
}
- AsyncTask执行一个task的流程图