您的位置:首页 > 移动开发 > Android开发

Android进阶系列--源码分析模板方法模式在AsyncTask的运用

2017-01-07 23:38 706 查看
模板方法之前我做了一些学习笔记,http://blog.csdn.net/sw5131899/article/details/52413701


模板方法的作用主要是规定子类的一些方法的调用顺序和父类封装好在何处调用。子类只需实现它的抽象方法,一些实际的逻辑就行,我们在使用AsyncTask的时候,只是需要实现一些加载前的方法,加载方法,和加载后的方法,那么我们为什么知道他们执行顺序呢?因为在AsncTask父类中已经有了调用顺序和执行线程。按照惯例,必须美女镇楼。



那么我们直接开始撸AsncTask源码吧。
AsyncTask是一个抽象类。那么创建一个它的子类,有需要可以实现一些它的方法。这里我把所有会用到的都写了,然后来吕一遍流程。 一个异步任务的执行一般包括以下几个步骤:

1.execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。

2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。

3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。

4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。

5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。

在使用的时候,有几点需要格外注意:

1.异步任务的实例必须在UI线程中创建。

2.execute(Params... params)方法必须在UI线程中调用。

3.不要手动调用onPreExecute(),doInBackground(Params... params),onProgressUpdate(Progress... values),onPostExecute(Result result)这几个方法。

4.不能在doInBackground(Params... params)中更改UI组件的信息。

5.一个任务实例只能执行一次,如果执行第二次将会抛出异常。

public class MyAsyncTask extends AsyncTask {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}

@Override
protected void onCancelled() {
super.onCancelled();
}

@Override
protected Object doInBackground(Object[] params) {
return null;
}
}


使用的时候都是调用execute("网址");那先看看execute这个方法。

@MainThread

public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }


@MainThread是线程注解,表示execute这个方法运行在主线程中。executeOnExecutor看看这个方法。

@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
............

mStatus = Status.RUNNING;

onPreExecute();

mWorker.mParams = params;
exec.execute(mFuture);

return this;
}
这个方法也是在主线程中运行的。并且调用了onPreExecute();这就是在下载前会触发的方法。比如一些加载PorgressBar就在这里设置。
@MainThread
protected void onPreExecute() {
}


onPreExecute也是在主线程执行的。mWorker是AsyncTask构造方法里里创建的。mWorker.mParams = params;exec.execute(mFuture);exec是一个线程池在静态代码块被初始化的,传入了mFuture。

static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
mFuture在初始化的时候,传入了mWorker  工作线程。和Runnable是一样。Runnable回调run方法。而mWorker  回调call()方法。call里面又执行了doInBackground方法。
public AsyncTask() {
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;
}
};

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);
}
}
};
}

@WorkerThread
protected abstract Result doInBackground(Params... params);
doInBackground是在工作线程中,也就是非主线程里执行。在调用doInBackground的底层调用了publishProgress。
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will not be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
而在这个方法里,使用了Handler发送消息,MESSAGE_POST_PROGRESS。那我们看看消息处理机制咋处理的
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;
}
}
}
result.mTask.onProgressUpdate(result.mData);调用了onProgressUpdate在主线程更新UI。当下载完成之后,也就是在finally中调用了postResult();
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);
}

private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}


然后采用Handler发送消息,完成了下载任务。
@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;
}
}


在消息处理机制会调用result.mTask.finish(result.mData[0]);
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
finish中会对当前任务的状态进行判定,到底是完成了还是取消了。完成了就会调用onPostExecute(result)。取消了就会调用onCancelled(result)。
@MainThread
protected void onPostExecute(Result result) {
}
onPostExecute也是在主线程中执行的,也就是说,在AsyncTask的几个方法中,只有doInBackGround是在子线程中,其他的都是在主线程中。这就是分析源码的好处,不用听别人说而去可以记结论,可以自己推出结论。一步一步往上走,似魔鬼的步伐。哈哈~~

参考:http://blog.csdn.net/yahohi/article/details/9031725   作者: wangicter
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息