Android-myLooper()与getMainLooper() [英] Android - myLooper() vs getMainLooper()

查看:79
本文介绍了Android-myLooper()与getMainLooper()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请澄清一下,但是如果我调用 Looper.myLooper() Looper.getMainLooper()的Android活动是在MAIN Thread上,则返回相同的引用,对吗?他们是一样的东西?我知道我永远不必通常调用这些,因为Android会解决这个问题,但是我想知道从主线程调用它们时它们有何不同?

Just clarifying but in an Android activity on MAIN Thread if I call Looper.myLooper() vs Looper.getMainLooper() the return the same reference, right? they are the same thing? I know I would never have to call these usually as Android takes care of this but I'd like to know how they differ when being called from the main thread?

如果从主线程中我调用

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

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

They both give the same runtime exception so I'm assuming they are the same reference:

原因:java.lang.RuntimeException:不允许退出主线程.

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

任何人都可以确认吗?

推荐答案

您已在文档中对其进行了描述:

You have it described in the docs:

getMainLooper()

返回应用程序的主循环程序,该循环程序位于应用程序的主线程中.

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

myLooper()

返回与当前线程关联的Looper对象.如果调用线程未与Looper关联,则返回null.

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

关于getMainLooper()是否有用,我可以向您保证.如果您在后台线程上执行一些代码并想要在UI线程上执行代码,例如更新用户界面,请使用以下代码:

As for whether getMainLooper() is of any use, I can assure you it really is. If you do some code on a background thread and want to execute code on the UI thread, e.g. update UI, use the following code:

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

当然,还有其他方法可以实现这一目标.

Of course, there are other ways of achieving that.

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

Another use is, if you want to check if the currently executed code is running on the UI thread, e.g. you want to throw / assert:

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

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

这篇关于Android-myLooper()与getMainLooper()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆