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

后端 未结 1 732
闹比i
闹比i 2021-02-06 02:55

I keep having the following memory leak as displayed by LeakCanary, when I go from my splash screen to the mainactivity. I understand that this is an expected leak due to fault

相关标签:
1条回答
  • 2021-02-06 03:00

    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.

    0 讨论(0)
提交回复
热议问题