AsyncTask 进行耗时操作和UI 更新
相信各位对 AsyncTask 不会陌生,虽然它有如下弊端:
1. 如果在activiy内部new 一个AsyncTask, 横竖屏切换生成一个新的activity,等结果返回时,处理不好容易出现NPE。
2. 容易出现内存泄漏,如果AsyncTask 进行比较耗时的IO操作(网络操作, 打开一个文件等等),在activity onDestroy的时候没有cancel的话,
导致该Activity不能被GC回收(AsyncTask 在Activity内部执行耗时操作)。
3. 如果调用 executeOnExecutor, 如果等待queue里面的请求过多没有得到及时处理,容易造成RejectException, 具体原因我在我的博客已经有所介绍(AsyncTask RejectedExecutionException 小结)。
闲话少说, 本文的重点不在于介绍AsyncTask的优缺点,而是一直有一个问题困扰我,为什么AsyncTask 里面既能进行UI 操作,又能进行耗时的操作。
让我们从代码角度来分析这个问题, 首先看他的构造函数:
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);
}
}
};
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
public class FutureTask<V> implements RunnableFuture<V>
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
从上面的代码可以看出, mWorker 实际上就是一个 Callable, 而 mFuture 就是一个Thread, 构造函数中将Callable 作为参数传给了 FutureTask,下面
我们看看FutureTask 中的相关实现:
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
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);
}
} 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);
}
}
protected void set(V v) {
if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
outcome = v;
U.putOrderedInt(this, STATE, NORMAL); // final state
finishCompletion();
}
}
private void finishCompletion() {
// 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;
}
}
done();
callable = null; // to reduce footprint
}
可以看到 result = c.call(); 在run方法中被调用, 实际就是 result = doInBackground(mParams); 被调用,因为该方法是在子线程里面执行,所以可以执行耗时操作。 继续读代码,call-> set(result) -> finishCompletion->done()-> postResultIfNotInvoked-> postResult
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
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.wh所以at) {
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;
}
}
}
相信上面的代码大家都能看懂,值得说明的是,因为 InternalHandler的构造函数使用 mainlooper,所以 handleMessage 当然可以进行UI 操作。
继续看源码:
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
总结一下,虚函数 doInBackground 在Thread(FutureTask)run方法执行,所以能进行耗时操作,而InternalHanlder 通过获得mainlooper,在 handleMessage中调用 onPostExecute 从而保证了UI 操作可以在onPostExecute执行。这个过程实际就是模板模式。

AsyncTask 进行耗时操作和UI 更新的更多相关文章
- AsyncTask 处理耗时操作&&显示进度条
在Android中实现异步任务机制有两种,Handler和AsyncTask.优缺点自己百度,推荐使用AsyncTask. private ProgressDialog dialog; //新建一个对 ...
- RxJava2-后台执行耗时操作,实时通知 UI 更新(一)
一.前言 接触RxJava2已经很久了,也看了网上的很多文章,发现基本都是在对RxJava的基本思想介绍之后,再去对各个操作符进行分析,但是看了之后感觉过了不久就忘了. 偶然的机会看到了开源项目 Rx ...
- Winform 界面执行耗时操作--UI卡顿假死问题
UI卡顿假死问题 误区1:使用不同的线程操作UI控件和耗时操作(即,跨线程操作UI控件CheckForIllegalCrossThreadCalls = false;), 注意:此处只是为了记录... ...
- iOS开发创建UI的耗时操作处理
项目中有网络请求.读写操作等一系列耗时操作时,为了避免阻塞主线程,我们会把这些耗时操作放到子线程中去处理,当处理完成后,再回到主线程更新UI,这样就不会阻塞主线程.但是创建UI的时候一般都是在主线程中 ...
- C#.NET使用Task,await,async,异步执行控件耗时事件(event),不阻塞UI线程和不跨线程执行UI更新,以及其他方式比较
使用Task,await,async,异步执行事件(event),不阻塞UI线程和不跨线程执行UI更新 使用Task,await,async 的异步模式 去执行事件(event) 解决不阻塞UI线程和 ...
- Android AsyncTask 异步任务操作
1:activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi ...
- android异步任务处理(网络等耗时操作)
在实际应用中经常会遇到比较耗时任务的处理,比如网络连接,数据库操作等情况时,如果这些操作都是放在主线程(UI线程)中,则会造成UI的假死现象(android4.0后也不许放在UI线程),这可以使用As ...
- runloop事件、UI更新、observer与coranimation
一.触摸事件派发与视图绘制打包 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ __dispatchPreprocessedEve ...
- 深入理解android的UI更新机制
深入理解android的UI更新机制 由问题开始: 如何更新android UI? 可以通过如下方法: 在主线程里直接操作UI控件. handler.post(Runnable) runOnUiThr ...
随机推荐
- docker run -v参数
挂载目录(直接给例子吧) -v=[]:绑定挂载目录 宿主机绑定: -v<host>:<container>:[rw|ro] 在Docker中新建一个共享的卷: -v /< ...
- 使用win10的开始屏幕,在系统中设置简洁、快捷桌面
前几天入手了一个本本,由于之前电脑使用的柠檬桌面软件和现在本本的分辨率不适应,意外发现win10自带的开始屏幕整理桌面也是很有意思,再加上触摸板的手势,瞬间觉得整个电脑都清洁许多.废话少说,开始上料. ...
- python-Word模板填充-docxtpl
docxtpl 按指定的word模板填充内容 安装 pip install docxtpl 示例 from docxtpl import DocxTemplate data_dic = { 't1': ...
- webpack 4.X 与 Vue 2.X结合
# Vue.js ## 注意: 有时候使用`npm i node-sass -D`装不上,这时候,就必须使用 `cnpm i node-sass -D` ## 在普通页面中使用render函数渲染组件 ...
- mysql用户管理和pymysql模块
一:mysql用户管理 mysql是一个tcp的服务器,用于操作服务器上的文件数据,接收用户端发送的指令,而接收指令时就 需要考虑安全问题. 在mysql自带的数据库中有4个表是用于用户管理的,分别是 ...
- 蚂蚁风险大脑亮相ATEC城市峰会:为数字经济时代做好“安全守护”
2019年1月4日,以“数字金融新原力(The New Force of Digital Finance)”为主题的蚂蚁金服ATEC城市峰会在上海隆重举行.大会聚焦金融数字化转型,分享新技术的发展趋势 ...
- document.getElementById动态的Node集合随时变化, 和document.querySelector静态的后续无法变化
1. W3C 标准querySelectorAll 属于 W3C 中的 Selectors API 规范 [1].而 getElementsBy 系列则属于 W3C 的 DOM 规范 [2]. 2. ...
- sqlite3如何判断一个表是否已经存在于数据库中 C++
SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='table_name';cnt will return 0 ...
- BaseDao封装
1.lombok 1) 在pom.xml中导入依赖 <!--导入lombok--> <!-- https://mvnrepository.com/artifact/org.proje ...
- linux基础命令连接命令ln
ln -s /etc/issue /tmp/issue.soft 创建文件/etc/issue 的软连接/tmp/issue.soft 不带-s 生成硬链接文件. 软连接类似于windows的 ...