如果Handler使用不当,会导致内存泄漏,直至内存溢出。因此,为了避免这种情况的发生,Handler要定义为static的,并且要是弱引用。本文用内部类的方式给出。
static class MyHandler extends Handler {
WeakReference<YourActivity> mActivity;
MyHandler(YourActivity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
YourActivity mAddActivity = mActivity.get();
if (msg.what == 0) {
mAddActivity.tv_save.setEnabled(true);
//你自己的代码逻辑
}
}
}
private MyHandler myHandler = new MyHandler(YourActivity.this);
这就搞定了,不会导致内存泄漏