平时我们习惯直接在 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使用会报一个提示,你注意到了么?你直接就可以拿非静态内部类持有外部类引用去解释内存泄漏了。