getMainLooper() 作为一个方法,它会根据你调用它的方式返回相同的结果,所以你可以认为两者是相同的,因为从上下文中返回 Looper 会在返回 Looper 时得到相同的结果从应用程序中获取它,为了更好地查看Looper 类并查看它如何返回循环器:
private static Looper sMainLooper;
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException(
"The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
public static Looper myLooper() {
return sThreadLocal.get();
}
当查看ThreadLocal.class 中的get() 方法时:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T) e.value;
}
return setInitialValue();
}
和Thread.currentThread(); 根据Thread.class 文档:
返回:
当前正在执行的线程。
这是在运行android的情况下保存上下文的线程。
毕竟,我发现困扰您的不是如何获得主循环器,而是在处理循环器时应该遵循的最佳实践是什么,例如何时使用getMainLooper() 以及何时使用@987654332 @,as described here:
Looper.prepareMainLooper() 在主 UI 线程中准备 looper。安卓
应用程序通常不调用此函数。由于主线程有
它的 looper 早在第一个活动、服务、提供者或
广播接收器已启动。
但是 Looper.prepare() 在当前线程中准备 Looper。在这之后
函数被调用,线程可以调用 Looper.loop() 开始处理
带有处理程序的消息。
你也应该知道getMainLooper()和myLooper()、as described here的区别:
getMainLooper
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.