gpt4 book ai didi

android - 获得 Looper 的最佳做法是什么?

转载 作者:行者123 更新时间:2023-11-30 00:59:37 28 4
gpt4 key购买 nike

我已经尝试了 mContext.getMainLooper()Looper.getMainLooper()。两者都返回相同的结果,但我想知道哪种方法正确?

我还从 Android 开发人员链接中阅读了这篇文章 thisthis :

For Looper.getMainLooper():

Looper getMainLooper () Returns the application's main looper, which lives in the main thread of the application.

For mContext.getMainLooper():

Looper getMainLooper () Return the Looper for the main thread of the current process. This is the thread used to dispatch calls to application components (activities, services, etc). By definition, this method returns the same result as would be obtained by calling Looper.getMainLooper().

最佳答案

getMainLooper() 作为一个方法,它会根据你调用它的方式返回相同的结果,所以你可以认为两者是一样的,因为从上下文中返回 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文档:

Returns: the currently executing thread.

在运行 android 的情况下,哪个线程持有上下文。


毕竟,我发现应该困扰您的不是如何获得主循环器,而是处理循环器时应该遵循的最佳实践是什么,例如何时使用 getMainLooper() 以及何时使用 Looper.prepare()as described here :

Looper.prepareMainLooper() prepares looper in main UI thread. Android applications normally do not call this function. As main thread has its looper prepared long before first activity, service, provider or broadcast receiver is started.

But Looper.prepare() prepares Looper in current thread. After this function is called, thread can call Looper.loop() to start processing messages with Handlers.

你还应该知道getMainLooper()myLooper() 之间的区别,as described here :

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.

关于android - 获得 Looper 的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39613713/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com