美文网首页
Android InputMethodmanager 引发的内存

Android InputMethodmanager 引发的内存

作者: 瀚宇恒翼 | 来源:发表于2018-12-26 16:02 被阅读0次

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

              } 

        }

    相关文章

      网友评论

          本文标题:Android InputMethodmanager 引发的内存

          本文链接:https://www.haomeiwen.com/subject/mmghlqtx.html