InputMethodmanager 引发的内存泄露是 Android 输入法的系统 bug,在15 <= API <= 23 中都存在。
解决方案:通过反射来拿到这个 View 并且置空。
@Override
protected void onDestroy() {
super.onDestroy();
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
String[] fileds = {"mCurRootView", "mServedView", "mNextServedView"};
try {
for (String filedStr : fileds) {
Field field = InputMethodManager.class.getDeclaredField(filedStr);
field.setAccessible(true);
Object mCurRootView = field.get(im);
if (mCurRootView != null && mCurRootView instanceof View) {
Context context = ((View) mCurRootView).getContext();
if (context == this) {
field.set(im, null);
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}