This Handler class should be static or leaks might occur 解决办法

平时我们习惯直接在 activity 中 new handler() 或 extends handler 使用,而 "This Handler class should be static or leaks might occur" 属于一种提示信息,平时我们都可能不太关注(本人也是,但是最近面试中被问到,所以才来了解一下)。


This Handler class should be static or leaks might occur (null) less... (Ctrl+F1) 

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. 


首先解释下这句话This Handler class should be static or leaks might occur,大致意思就是说:Handler类应该定义成静态类,否则可能导致内存泄露。

从这我们就可以看出,这尼玛不就是匿名内部类引用的问题么,这么小的一个问题,我就从2个候选人中pass掉了,后悔死了,看来这种小知识还是要从点滴做起啊,从今天开始做一个记录生活点滴的男人。。。扯远了,既然知道了我们该如何来解决呢。。。


第一种方法按照它的提示我们直接就把 handler 加 static 修饰即可

static Handler handler = new Handler();


第二种方法则是重新写一个类,不写内部类,这种方式也是国外大牛们所推荐的

public class MyHandler extends Handler {

    public static final int MSG_PLAY = 100;

    WeakReference
   
   
    
     mActivity;

    public MyHandler(Activity activity) {
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
        Activity theActivity = mActivity.get();
        if(theActivity == null)
            return;
        switch (msg.what) {
            case MSG_PLAY:
                if(theActivity instanceof MainActivity)
                    ((MainActivity)theActivity).doSomething();
                break;
            default:
                break;
        }
    }
}
   
   



好了,下次面试要是谁问你handler直接new出来或extends使用会报一个提示,你注意到了么?你直接就可以拿非静态内部类持有外部类引用去解释内存泄漏了。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值