通过Android Profile+MAT定位到InputMethodManager泄漏Activity。
- 解决方案
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import java.lang.reflect.Field;
/**
* 内存泄漏工具类
* 作者: FebMaple on 26/12/2018.
* 版权: FebMaple
* ====================================================
*/
public class MemoryLeakUtil {
/**
* fix InputMethodManager leak memory
*
* @param context
*/
public static void fixInputMethodMemoryLeak(Context context) {
if (context == null)
return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager == null)
return;
String[] viewArr = new String[]{"mCurRootView", "mServedView", "mNextServedView", "mLastSrvView"};
Field field;
Object fieldObj;
for (String view : viewArr) {
try {
field = inputMethodManager.getClass().getDeclaredField(view);
if (!field.isAccessible()) {
field.setAccessible(true);
}
fieldObj = field.get(inputMethodManager);
if (fieldObj != null && fieldObj instanceof View) {
View fieldView = (View) fieldObj;
if (fieldView.getContext() == context) {// 被InputMethodManager持有引用的context是想要目标销毁的
field.set(inputMethodManager, null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在泄漏的activity ondestroy内添加
@Override
protected void onDestroy() {
MemoryLeakUtil.fixInputMethodMemoryLeak(this);
super.onDestroy();
}