几天以来,我试图弄清楚如果我执行代码到底会发生什么
void function(){
//somePreExecutionCode
new Handler().post(new Runnable(){
@Override
public void run(){
//someCode
}
});
}
看起来它并没有阻塞 UI,因此调用 function() 的按钮不会卡在单击的位置,直到 someCode 完成。
但是,如果 somePreExecutionCode 启动进度条,则当 someCode 完成时,进度条会在同一时刻显示。
我知道,有 AsyncTasks,但是还有其他可能性吗?
和有什么区别
new Handler().post
and
View.post
?
当创建一个Android应用程序时,系统会创建一个执行的主线程。该线程称为 UI 线程,所有与 UI 相关的操作都发生在该线程上,以避免同步问题。
A Looper http://developer.android.com/reference/android/os/Looper.html实例是在此线程上创建的,该线程有一个消息队列 http://developer.android.com/reference/android/os/MessageQueue.html数据结构。 Looper会处于无限循环等待读取Message http://developer.android.com/reference/android/os/Message.html / Runnable http://developer.android.com/reference/java/lang/Runnable.html实例发布于消息队列 http://developer.android.com/reference/android/os/MessageQueue.html。添加消息7 /Runnable http://developer.android.com/reference/java/lang/Runnable.html到消息队列,Handler http://developer.android.com/reference/android/os/Handler.html用来。
当您创建 Handler 实例时,它将与当前执行线程以及在该特定线程上创建的 Looper 实例相关联。
因此,当您通过 Handler 发布消息时,该消息将被添加到 MessageQueue 中,Looper 将按 FIFO 顺序读取消息并将其传递到目标。
new Handler().post() 和 View.post 有点不同。
- 当您通过 View.post 发布消息时,可以保证消息将发布到 UI 线程消息队列上,因为它内部使用在 UI 线程上创建的 Handler 实例。
- 如果您在 UI 线程上创建 Handler 实例并在任何线程上使用它发布消息,则消息将被发布到 UI 线程的 MessageQueue 中。
- 如果您在非 UI 线程上创建 Handler 实例并使用它发布消息,它们将被发布到非 UI 线程的 MessageQueue 上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)