请问这种写法会不会导致内存泄露:
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);
}
No, this is the standard way to use weak references.
You don’t need weak references. Just clear the message when destroying
The original poster should pay attention to Google’s official demo and lint tips