请问这种写法会不会导致内存泄露:
static class MyHandler extends Handler {
WeakReference<Activity> mWeakReference = null;
public MyHandler(SampleActivity activity) {
mWeakReference = new WeakReference<Activity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
SampleActivity activity = (SampleActivity) mWeakReference.get();
if(activity == null) {
return;
} else {
if(msg.what == 0) {
//do something
}
}
}
}
然后我在onCreate方法中初始化一个MyHandler的对象:
private MyHandler mHandler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initViews();
mHandler = new MyHandler(this);
}
不会了,这是标准的使用弱引用的方式。
可以不用弱引用 在销毁的时候 清空消息就行了
楼主去关注一下google的官方demo,以及lint的提示