Android - myLooper() 与 getMainLooper()

标签 android android-looper

只是澄清一下,但是在主线程上的 Android Activity 中,如果我调用 Looper.myLooper()Looper.getMainLooper() 返回相同的引用,对吗?他们是一样的东西?我知道我永远不必调用它们,因为 Android 会处理这些,但我想知道从主线程调用时它们有何不同?

如果我从主线程调用

Looper.myLooper().quit();
// or
Looper.getMainLooper().quit();

它们都给出相同的运行时异常,所以我假设它们是相同的引用:

Caused by: java.lang.RuntimeException: Main thread not allowed to quit.

谁能证实一下?

最佳答案

你在文档中描述了它:

getMainLooper()

Returns the application's main looper, which lives in the main thread of the application.

myLooper()

Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.

至于getMainLooper()有没有用,我可以向你保证它确实有用。如果您在后台线程上执行一些代码并希望在 UI 线程上执行代码,例如更新 UI,使用以下代码:

new Handler(Looper.getMainLooper()).post(new Runnable() {
  // execute code that must be run on the UI thread
});

当然,还有其他方法可以实现。

另一个用途是如果你想检查当前执行的代码是否在 UI 线程上运行,例如你想抛出/断言:

boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();

boolean isUiThread = Looper.getMainLooper().isCurrentThread();

关于Android - myLooper() 与 getMainLooper(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322498/

相关文章:

java - 与 post 与 postDelayed 保持时间间隔

java - 如何在群聊中显示消息和时间?

android - 带有 AsyncTask 和 SQLite 游标的 NullPointerException

java - Android单元测试: Mock context that also returns a looper

android - 什么是 E/AbstractTracker : Can't create handler inside thread that has not called Looper. prepare()?

java - 来自后台线程的处理程序 postDelayed()

android - HandlerThread 中的 NullPointerException

android - 在 android wear 中处理屏幕暗淡/屏幕锁定

安卓 | TextView.setText() 不起作用

android - 信号 11 (SIGSEGV),代码 1 (SEGV_MAPERR),故障地址 0x7f4485ff1820