Android - myLooper() 与 getMainLooper()
Android - myLooper() vs getMainLooper()
只是澄清一下,但是在主线程的 Android activity 中,如果我调用 Looper.myLooper()
与 Looper.getMainLooper()
和 return 相同的引用,对吗?他们是一样的东西?我知道我通常永远不必调用这些,因为 Android 会处理这个,但我想知道从主线程调用时它们有何不同?
如果我从主线程调用
Looper.myLooper().quit();
// or
Looper.getMainLooper().quit();
它们都给出相同的运行时异常,所以我假设它们是相同的引用:
Caused by: java.lang.RuntimeException: Main thread not allowed to quit.
谁能证实一下?
Looper.getMainLooper()
很方便 API 获取附加到主线程的循环程序 activity.It 当您想从后台线程在主线程上执行某些代码时很有用.
通常使用如下:
new Handler(Looper.getMainLooper()).post(task);
Looper.myLooper()
是 api 将循环器附加到当前线程
您在文档中对其进行了描述:
Returns the application's main looper, which lives in the main thread of the application.
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 UI thread
});
当然,还有其他方法可以实现。
另一个用途是,如果你想检查当前执行的代码是否是 UI 线程上的 运行,例如你想抛出/断言:
boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();
或
boolean isUiThread = Looper.getMainLooper().isCurrentThread();
如果在main thread
中调用这两个方法,它们是同一个对象!您可以在ActivityThread.java
、Looper.java
和ThreadLocal.java
.
的源代码中找到答案
只是澄清一下,但是在主线程的 Android activity 中,如果我调用 Looper.myLooper()
与 Looper.getMainLooper()
和 return 相同的引用,对吗?他们是一样的东西?我知道我通常永远不必调用这些,因为 Android 会处理这个,但我想知道从主线程调用时它们有何不同?
如果我从主线程调用
Looper.myLooper().quit();
// or
Looper.getMainLooper().quit();
它们都给出相同的运行时异常,所以我假设它们是相同的引用:
Caused by: java.lang.RuntimeException: Main thread not allowed to quit.
谁能证实一下?
Looper.getMainLooper()
很方便 API 获取附加到主线程的循环程序 activity.It 当您想从后台线程在主线程上执行某些代码时很有用.
通常使用如下:
new Handler(Looper.getMainLooper()).post(task);
Looper.myLooper()
是 api 将循环器附加到当前线程
您在文档中对其进行了描述:
Returns the application's main looper, which lives in the main thread of the application.
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 UI thread
});
当然,还有其他方法可以实现。
另一个用途是,如果你想检查当前执行的代码是否是 UI 线程上的 运行,例如你想抛出/断言:
boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();
或
boolean isUiThread = Looper.getMainLooper().isCurrentThread();
如果在main thread
中调用这两个方法,它们是同一个对象!您可以在ActivityThread.java
、Looper.java
和ThreadLocal.java
.