使用Handler中遇到的问题分析

本文详细分析了在使用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配合弱引用来避免内存泄露。

引言

相信很多童鞋在使用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 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值