在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