华为手机 Leak android.gestureboost.GestureBoostManager内存泄露解决

  1. 再用华为手机测试的时候leakcanary,老是提示GestureBoostManager,这个类的mContext引用当前Activity,导致的内存泄露。

《华为手机 Leak android.gestureboost.GestureBoostManager内存泄露解决》 device-2017-05-27-152211.png

于是翻阅源码,也没有找到这个类,看来应该是EMUI里面的类,可惜EMUI应该没有开源,所以也看不了源码,那么该如何解决这个内存泄露呢?说起来也简单,只要将这个类引用我们的Activity给去掉,内存泄露不就解决了嘛。

首先GestureBoostManager,我们无法主动的调用相关api方法,断开这个引用,所以只能使用反射,将这个引用剪掉!

上代码:

 /**
     * 修复华为手机内存的泄露
     */
    public void fixHuaWeiMemoryLeak(){
        //测试
        try {
            Class<?> GestureBoostManagerClass = Class.forName("android.gestureboost.GestureBoostManager");
            Field sGestureBoostManagerField = GestureBoostManagerClass.getDeclaredField("sGestureBoostManager");
            sGestureBoostManagerField.setAccessible(true);
            Object gestureBoostManager = sGestureBoostManagerField.get(GestureBoostManagerClass);
            Field contextField = GestureBoostManagerClass.getDeclaredField("mContext");
            contextField.setAccessible(true);
            if (contextField.get(gestureBoostManager)==this) {
                contextField.set(gestureBoostManager, null);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }

    }

注意:为了保险起见,我们可以在自己的BaseActivity的onDestroy()方法里面,剪掉这个引用,再减掉之前,添加了一个判断GestureBoostManager是否引用当前的Activity,如果是,那就立马剪掉,否者的话,咱就不处理。

    原文作者:元涛
    原文地址: https://www.jianshu.com/p/17760e8fd1cd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞