@SuppressLint("HandlerLeak"),或Handler使用有警告;

随手写个Handler,然后飘黄,看着挺难受(黄色警告的大概意思:Handler可能会内存泄漏,推荐你用静态内部类+实例化弱引用);

This Handler class should be static or leaks might occur (anonymous android.os.Handler) less...
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.

这个处理程序类应该是静态的,否则可能会发生泄漏(android.os.Handler)

由于这个处理程序声明为内部类,它可能会阻止外部类被垃圾收集。如果处理程序对主线程以外的线程使用循环程序或MessageQueue,则没有问题。如果处理程序使用主线程的Looper或MessageQueue,则需要修复处理程序声明,如下所示:将处理程序声明为静态类;在外部类中,实例化对外部类的弱引用,并在实例化处理程序时将此对象传递给处理程序;使用WeakReference对象引用外部类的所有成员。

不管,先提示一下:

这个注解看着也难受;

按照它的警告修改一下(推荐使用):

   //静态内部类 弱引用
    private BleHandler mHandler = new BleHandler(getApplication());
    static class BleHandler extends Handler{

        WeakReference weakReference;
        public BleHandler(Context context){
           weakReference = new WeakReference(context);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference == null)return;
        }
    }

还可以这样去写,没有警告:

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            return false;
        }
    });

 

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值