当我们使用Handler的时候,习惯于这样写
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
};
};
在Lint检查时会有这样的警告:
This Handler class should be static or leaks might occur
当消息队列中有消息排队的时候,这些Message就保持了对handler的引用,而handler在这里是个内部类,它又保持了对外部类的引用。这样就容易造成Activity或者service无法被GC,引起内存泄露。
Lint给出的建议是让handler是静态的并且保持弱引用。应该如此解决:
static class MyHandler extends Handler{
WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
if(activity == null){
return;
}
switch (msg.what) {
default:
break;
}
}
}
private MyHandler handler = new MyHandler(this);