前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Handler Looper.prepareMainLooper();源码分析

Handler Looper.prepareMainLooper();源码分析

作者头像
毛大姑娘
发布2020-09-10 15:42:49
1.3K0
发布2020-09-10 15:42:49
举报
文章被收录于专栏:向全栈出发向全栈出发

我们常说子线程使用Handler之前,需要先进行Looper.prepare();而主线程不需要额外添加代码,为什么主线程不需要手动操作Looper呢?它又是在哪里做prepare操作的呢?

我们来看一下。

(一)相关源码

Activity启动的源头是来自ActivityThread.java里面的main方法。main方法里会调用Looper.prepareMainLooper();

下面是通过Looper.prepareMainLooper();跟进去的源码。

代码语言:javascript
复制
    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }




Looper.java

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }



ThreadLocal.java
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }


ThreadLocal.java
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
ThreadLocal.java
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }



Looper.java

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    /**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }




ThreadLocal.java
    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }



ThreadLocal.java
    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }



ThreadLocal.java
    protected T initialValue() {
        return null;
    }

(二)总结

Looper.prepareMainLooper();与Looper.prepare();有什么区别?

区别有两点:

  1. prepareMainLooper()里面对初始化Looper进行了同步,而且只允许初始化一次,多次初始化会抛出异常;
  2. Looper.prepareMainLooper()里面prepare(false);传入的参数,与Looper.prepare()里面prepare(true);传入的参数值不同。这个参数是quitAllowed,这个参数最终会传入到MessageQueue里面作为它的属性,参数的含义为是否允许退出,如果为true,允许MessageQueue在清除掉所有消息之后退出。否则就会抛出异常。

下面是相关源码片段:

代码语言:javascript
复制
Looper.java
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }



Looper.java
    public static void prepare() {
        prepare(true);
    }



Looper.java
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }





MessageQueue.java
    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

下一次讲Looper与Handler源码分析,敬请期待!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年05月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • (一)相关源码
  • (二)总结
    • Looper.prepareMainLooper();与Looper.prepare();有什么区别?
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档