Heim > Fragen und Antworten > Hauptteil
请问这种写法会不会导致内存泄露:
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);
}