【问题标题】:What is the best practice to get Looper?获得 Looper 的最佳做法是什么?
【发布时间】:2016-09-21 10:16:36
【问题描述】:

我试过mContext.getMainLooper()Looper.getMainLooper()。 两者都返回相同的结果,但我想知道哪个应该是正确的方法?

我还从 Android 开发者链接 thisthis 中读到了这篇文章:

对于 Looper.getMainLooper():

Looper getMainLooper() 返回应用程序的主循环器,它 位于应用程序的主线程中。

对于 mContext.getMainLooper():

Looper getMainLooper() 返回主线程的Looper 当前进程。这是用于调度调用的线程 应用程序组件(活动、服务等)。根据定义, 此方法返回的结果与通过调用获得的结果相同 Looper.getMainLooper().

【问题讨论】:

  • 对我来说应该是Looper.getMainLooper(),因为它不需要上下文对象。根据定义,两者都是相似的,那么选择是你的。

标签: android android-context android-looper


【解决方案1】:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多