首页 > 其他 > 详细

在Activity的onCreate方法中调用Looper.prepare()方法会发生什么?

时间:2021-03-04 10:17:12      阅读:26      评论:0      收藏:0      [点我收藏+]

问题

在Activity的onCreate方法中调用Looper.prepare()方法会发生什么?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Looper.prepare();
    }

答案

会抛出以下异常信息

Caused by: java.lang.RuntimeException: Only one Looper may be created per thread

分析

每个应用启动的时候,都是由ActivityThread.main()进入,在main()方法中,调用了Looper.prepareMainLooper()以及Looper.loop()

    public static void main(String[] args) {
        //TODO 省略部分代码 
      
        Looper.prepareMainLooper();
        
        // 这里会开始执行Application、Activity生命周期流程
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        //TODO 省略部分代码
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

先看看Looper.prepareMainLooper()做了什么?

    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

可以看到调用了prepare(boolean quitAllowed)方法,该方法又做了什么呢?

    // sThreadLocal.get() will return null unless you‘ve called prepare().
    //TODO 蹩脚的翻译就是:如果没有调用prepare方法,sThreadLocal.get()会返回null。
    @UnsupportedAppUsage
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();


    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));
    }

sThreadLocal.get() != null可以了解到,如果已经创建了Looper对象,再次调用该方法时就会抛出异常信息

throw new RuntimeException("Only one Looper may be created per thread")

再回归到ActivityThread.main()方法,调用了Looper.prepareMainLooper()后执行attach()方法

    public static void main(String[] args) {
        //TODO 省略部分代码 
      
        Looper.prepareMainLooper();
        
        // 这里会开始执行Application、Activity生命周期流程
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        //TODO 省略部分代码
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

这里会开始执行Application、Activity生命周期流程,最后会进入到Activity的onCreate()方法中,这时调用Looper.prepare()就会抛出异常信息了。

在Activity的onCreate方法中调用Looper.prepare()方法会发生什么?

原文:https://www.cnblogs.com/chendd870172464/p/14465722.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!