我是Android新手.我想知道Looper课程的作用以及如何使用它.我已阅读Android Looper类文档,但我无法完全理解它.我在很多地方都看过它但却无法理解它的目的.任何人都可以通过定义目的来帮助我,Looper并且如果可能的话也给出一个简单的例子吗?
我是android新手,正在官方android网站上阅读演示应用程序.我遇到了一个Handler名为as 的类方法postDelayed(Runnable r, long milliseconds).
任何人都可以解释这种方法的作用吗?
我想知道Looper类如何实际处理Looper附加到的Thread中的Runnables(通过Handler类)?如果一个looper循环遍历其messageQueue,那么肯定会是该线程的阻塞操作?我想它本身必须执行一些线程技巧但是它如何将发布的Runnables run()方法添加到主机线程堆栈?
许多问题!任何帮助将非常感激.谢谢!
编辑:
通过Looper 类文件类,我看到下面的内容,这让我更加困惑,因为所有注释都指向在主线程中运行的looper,而且还在等待MessageQueue上的新消息时进行阻塞操作.这怎么不阻塞UI /主线程???
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
while (true) {
Message msg = …Run Code Online (Sandbox Code Playgroud) 今天我阅读了一些关于 Handler 和 Looper 如何协同工作的博客和源代码。
根据我所学到的,通过使用ThreadLocal魔法,我们可以在每个线程上只有一个 Looper 。通常Handler是在主线程中启动的,否则你必须手动启动或说,prepare将Looper放在一个单独的线程上,然后循环起来。
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
Run Code Online (Sandbox Code Playgroud)
真正让我困惑的是loop()主线程。当我在 Looper 的源代码中读到这个时。处理消息队列然后分派消息以供回调处理是一个无限循环。
根据这个/sf/answers/363578701/,Handler 和它的 Looper 在同一个线程中运行。
如果主线程出现死循环,岂不是阻塞了整个UI系统?
我知道我一定是傻到错过了什么。但如果有人能透露这背后的秘密,那就太好了。
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called …Run Code Online (Sandbox Code Playgroud)