引言
相信很多童鞋在使用handler的时候肯定遇到了不少的麻烦吧,比如:
1、Only one Looper may be created per thread;
2、Can’t create handler inside thread that has not called Looper.prepare();
3、handler导致的内存泄漏等。
那么今天就详细分析一下其中的原因,以记录又一次深深的掉入坑里无法自拔的囧态。
Only one Looper may be created per thread
这个问题还是比较好查找原因的,我们在使用的时候如果调用Looper.prepare()两次就会出现,通过查看源码来分析:
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));
}
可以看到prepare方法中代码非常少,首先是调用sThreadLocal.get()方法去取Looper,如果是null说明没有创建并存储,然后会新建一个Looper对象,然后存入sThreadLocal对象中;如果不是null说明Looper对象已经创建过了,这时候就会抛出Only one Looper may be created per thread异常。可见prepare()方法不能调用两次,如果调用两次就会抛出异常。
Can’t create handler inside thread that has not called Looper.prepare()
意思是不能在没有调用Looper.prepare()方法的线程中创建handler,那么继续通过源码分析:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final

本文详细分析了在使用Handler时遇到的常见问题,包括Only one Looper may be created per thread和Can’t create handler inside thread that has not called Looper.prepare()异常,以及主线程创建Handler为何无问题。此外,还深入探讨了Handler导致的内存泄漏问题,并提出了相应的解决策略,如使用removeCallbacks()、removeMessages()或声明静态Handler配合弱引用来避免内存泄露。
最低0.47元/天 解锁文章
6955

被折叠的 条评论
为什么被折叠?



