请问这种写法会不会导致内存泄露:
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的提示