Android memory leak on textview - LeakCanary (Leak can be ignored)

余生长醉 提交于 2019-12-03 02:59:53

From AndroidExcludedRefs.java:

  // TextLine.sCached is a pool of 3 TextLine instances. TextLine.recycle() has had at least two
  // bugs that created memory leaks by not correctly clearing the recycled TextLine instances.
  // The first was fixed in android-5.1.0_r1:
  // https://github.com/android/platform_frameworks_base/commit
  // /893d6fe48d37f71e683f722457bea646994a10bf

  // The second was fixed, not released yet:
  // https://github.com/android/platform_frameworks_base/commit
  // /b3a9bc038d3a218b1dbdf7b5668e3d6c12be5ee4

  // Hack: to fix this, you could access TextLine.sCached and clear the pool every now and then
  // (e.g. on activity destroy).

Step 1: Access TextLine.sCached

public static class Utils {
    private static final Field TEXT_LINE_CACHED;

    static {
        Field textLineCached = null;
        try {
            textLineCached = Class.forName("android.text.TextLine").getDeclaredField("sCached");
            textLineCached.setAccessible(true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        TEXT_LINE_CACHED = textLineCached;
    }

    public static void clearTextLineCache() {
        // If the field was not found for whatever reason just return.
        if (TEXT_LINE_CACHED == null) return;

        Object cached = null;
        try {
            // Get reference to the TextLine sCached array.
            cached = TEXT_LINE_CACHED.get(null);
        } catch (Exception ex) {
            //
        }
        if (cached != null) {
            // Clear the array.
            for (int i = 0, size = Array.getLength(cached); i < size; i ++) {
                Array.set(cached, i, null);
            }
        }
    }

    private Utils() {}
}

Step 2: Clear the pool

Call Utils.clearTextLineCache() when needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!