android - AppCompatTextView 在 API 22 上泄漏内存

标签 android memory-leaks leakcanary

由于 AppCompatTextView,我出现了内存泄漏 它没有点击监听器,只是一个普通的 TexView,其中包含一些文本。

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

enter image description here

我已经尝试过建议的解决方案 here但这没有帮助。

最佳答案

这是一个 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也。

关于android - AppCompatTextView 在 API 22 上泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35579204/

相关文章:

android - 带有 AlarmManager 的 IntentService

iphone - UIWebView 泄漏?有人可以确认吗?

android - BottomSheetDialogFragment内存泄漏(使用leakcanary)

android - zza.zza FirebaseAuthFallbackService 泄漏

android - 如何在相同的 xml 布局中将元素放在彼此之上?

java - 如何在 android studio 上启用泛型类型 <T>

android - 错误从服务启动 AlertDialog.Builder

ios - ARC 的内存问题

c# - 如果 .NET 中的 MemoryStream 未关闭,是否会产生内存泄漏?

android - 如何忽略 LeakCanary 中的某些类?