2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Asynctask源码级解析 深度探索源码之旅

Asynctask源码级解析 深度探索源码之旅

时间:2021-10-03 08:41:00

相关推荐

Asynctask源码级解析 深度探索源码之旅

常用方法:

1、onPreExecute方法是预加载,在主线程中执行

2、doInBackground运行在子线程中,执行耗时的操作,子线程中不能更新主UI界面

3、onProgressUpdate方法进度更新,运行在主线程中

4、onPostExecute结果处理,运行在主线程中,可以直接更新主UI

总结:Asynctask是通过线程池的原理来异步处理任务的,但在底层它的子线程是由java.util.concurrent包下的Callable接口子类实现的。

doInBackground是在Callable的实现类中回调的,所以执行在子线程中,而onProgressUpdate和onPostExecute两个方法是在handler中回调的因此执行在主线程,onPreExecute方法直接在父类中回调,所以也执行在主线程。

注意:子线程不能更新主线程UI

为什么呢?那就来看一下源码:

1、先看看onPreExecute在哪里被回调的。

public finalAsyncTask<Params,Progress,Result>executeOnExecutor(Executorexec,

Params... params) {

if(mStatus != Status.PENDING) {

switch(mStatus) {

caseRUNNING:

throw newIllegalStateException("Cannot execute task:"

+ " the taskis already running.");

caseFINISHED:

throw newIllegalStateException("Cannot execute task:"

+ " the taskhas already been executed "

+ "(a task canbe executed only once)");

}

}

mStatus = Status.RUNNING;

onPreExecute();//方法回调

mWorker.mParams = params;

exec.execute(mFuture);

return this;

}

结论:显然该方法不运行在子线程中

参数含义拓展:

第一参数Executor是一个线程池

An object that executes submitted Runnabletasks. This interface provides a way of decoupling task submission from themechanics of how each task will be run, including details of thread use,scheduling, etc. AnExecutoris normally used instead of explicitly creating threads. Forexample, rather than invokingnew Thread(new(RunnableTask())).start()for each of a set of tasks, you might use:

2、doInBackground运行在子线程中,执行耗时的操作,子线程中不能更新主UI界面

mWorker =newWorkerRunnable<Params,Result>() {

publicResult call()throwsException {

mTaskInvoked.set(true);

Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

//noinspection unchecked

returnpostResult(doInBackground(mParams));//方法回调

}

private staticabstract classWorkerRunnable<Params,Result>implementsCallable<Result> {

Params[] mParams;

}

英文版:

结论:显然该方法运行在子线程中,但原理不是Runnable接口,而是运行在和相似的Callable接口的实现类中。这两个接口属于不同的包,以及其他区别。

3、onProgressUpdate方法进度更新,运行在主线程中

privatestatic classInternalHandlerextendsHandler {

@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})

@Override

public void handleMessage(Message msg) {

AsyncTaskResultresult= (AsyncTaskResult) msg.obj;

switch(msg.what) {

caseMESSAGE_POST_RESULT:

// There is only one result

result.mTask.finish(result.mData[0]);//finish方法回调

break;

caseMESSAGE_POST_PROGRESS:

result.mTask.onProgressUpdate(result.mData);//源码方法回调

break;

}

}

}

因为handler运行在主线程而onProgressUpdate方法在handler中回调,所以onProgressUpdate方法运行在主线程,因此可以和主线程交互。

4、onPostExecute方法

private void finish(Resultresult) {

if(isCancelled()) {

onCancelled(result);

}else{

onPostExecute(result);//方法回调

}

mStatus = Status.FINISHED;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。