如果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);
最后,不要忘记要,要及时销毁这个handler
@Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null && mHandler.hasMessages(PROGRESS)) {
mHandler.removeMessages(PROGRESS);
}
}
这就搞定了,不会导致内存泄漏