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

What is the best practice to get Looper?

我试过 mContext.getMainLooper()Looper.getMainLooper()。 两者 return 结果相同,但我想知道哪种方法正确?

我也是从 Android 开发者那里读到的 link this and this:

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() 作为一个方法,它会 return 与你调用它的方式相同的结果,所以你可以认为两者是相同的,因为 returning Looper当从应用程序 returning 循环器时,从上下文中得到相同的结果,为了更好地查看 Looper class 并了解它是如何 returns循环器:

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()的区别,:

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.