对于近期排查内存泄漏时遇到的关于Handler使用不当造成内存泄漏的一些优化总结。代码看着确实比以前多了些,但只要能优化,咋都行。以下均使用静态内部类+弱引用的方式,解决Handler持有外部类引用导致的内存泄漏问题。
1.Activity中的使用
private Handler mHandler = new MainHandler(this);
private static class MainHandler extends Handler {
private WeakReference<MainActivity> activityWeakReference;
public MainHandler(MainActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (activityWeakReference == null) {
return;
}
// 若Activity被回收,此时Activity便为空
MainActivity mActivity = activityWeakReference.get();
if (mActivity == null) {
return;
}
mActivity.doHandleMessage(msg);
}
}
private void doHandleMessage(Message msg) {
switch (msg.what) {
case YOUR_ACTION:
// 业务处理
}
break;
default:
break;
}
}
2.Fragment中的使用
private Handler mHandler = new MyHandler(this);
private static class MyHandler extends Handler {
private final WeakReference<SettingVideoFragment> mFragment;
public MyHandler(SettingVideoFragment fragment) {
mFragment = new WeakReference<>(fragment);
}
@Override
public void handleMessage(@NonNull Message msg) {
SettingVideoFragment fragment = mFragment.get();//弱引用
if (fragment != null) {
switch (msg.what) {
case RESH_CAMERA_DATA:
log.E("刷新相机的列表");
fragment.showCameraData();
break;
default:
break;
}
}
}
}
3.其他类中的使用
private final Handler mHandler = new VideoCaptureHandler(this);
private static class VideoCaptureHandler extends Handler {
private final WeakReference<VideoCapture> mCaptureRef;
public VideoCaptureHandler(VideoCapture capture) {
mCaptureRef = new WeakReference<>(capture);
}
@Override
public void handleMessage(Message msg) {
VideoCapture capture = mCaptureRef.get();
if (capture != null) {
try {
if (msg.what == CAMERA_UNLOCKFOCUS) {
capture.isFocusing = false;
capture.mSensorControler.unlockFocus();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
msg.recycle();
}
}
}
}
如果还不放心,也可以在适当位置调用代码释放掉,双保险。
mHandler.removeCallbacksAndMessages(null);
mHandler = null;