AppCompatTextView 在 API 22 上泄漏内存

AppCompatTexView leaks memory on API 22

由于 AppCompatTextView 我有内存泄漏 它没有点击监听器,它只是一个普通的 TexView,里面有一些文本。

我能做些什么吗?这是一个错误还是我做错了什么?

我尝试了建议的解决方案 here 但没有帮助。

根据这个link: https://code.google.com/p/android/issues/detail?id=179272 泄漏似乎是由以下原因引起的:

It happens with anything which uses TextLine (TextView, descendants, Layout) with Spanned text. As SearchView uses a SpannableStringBuilder internally, it gets leaked.

希望对你有所帮助:)

这是一个 android 框架错误。 https://code.google.com/p/android/issues/detail?id=34731 它尚未修复,即使在支持库中也是如此。

修复如下:

public static void fixInputMethodManagerLeak(Context destContext) {
    if (destContext == null) {
        return;
    }

    InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm == null) {
        return;
    }

    String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
    Field f = null;
    Object obj_get = null;
    for (int i = 0; i < arr.length; i++) {
        String param = arr[i];
        try {
            f = imm.getClass().getDeclaredField(param);
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            obj_get = f.get(imm);
            if (obj_get != null && obj_get instanceof View) {
                View v_get = (View) obj_get;
                if (v_get.getContext() == destContext) {  // referenced context is held InputMethodManager want to destroy targets
                    f.set(imm, null);  // set empty, destroyed node path to gc
                } else {
                    // Not want to destroy the target, that is, again into another interface, do not deal with, to avoid affecting the original logic, there is nothing further for the cycle
                    Log.e(TAG, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext() + " dest_context=" + destContext);
                    break;
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

这样称呼它:

@Override
protected void onDestroy() {
    super.onDestroy();
    //if you get memory leak on configuration change too, remove the if clause.
    if (isFinishing()) {
        fixInputMethodManagerLeak(this);
    }
}

也看看this question