Handler 相关的问题

1. Android Studio 不能自动 import class android.os.Handler,而是直接 import class java.util.logging.Handler,这是什么鬼?难道是因为 Handler 实例不能直接 new?
似乎是 Android Studio 的一个缺陷,手动 import 吧
 
 
2. Android Studio 黄色警告,可能会有泄漏,这个怎么处理?
final android.os.Handler myHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        if (msg.what == 0x123) {
            // do sth
        }
        super.handleMessage(msg);
    }
};
Handler reference leaks
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. 
If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. 
If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: 
    Declare the Handler as a static class; 
    In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; 
    Make all references to members of the outer class using the WeakReference object.
再看吧。。。
     
3. 因为只由主线程可以对UI进行修改,所以是不是只由主线程有自己的 Looper,“程序员自己启动的子线程,程序员必须自己创建一个Looper对象,并启动”的意义何在?子线程并不需要Looper来进行UI修改啊,不是也改不了么?是自定义的Activity要这么来做?
的确可以在不需要使用到Looper的时候进行Handler的使用,另外在子线程中使用handler 然后更新UI,还是会导致异常,但是使用 Toast.show() 没有问题。
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值