Android InputMethodmanager 引发的内存泄露

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();

          } 

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容