InputMethodmanager 引發(fā)的內(nèi)存泄露是 Android 輸入法的系統(tǒng) 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();
? ? ? ? ? }?
? ? }