华为手机 Leak android.gestureboost.G

作者: 元涛 | 来源:发表于2017-05-27 16:42 被阅读188次
    1. 再用华为手机测试的时候leakcanary,老是提示GestureBoostManager,这个类的mContext引用当前Activity,导致的内存泄露。
    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,如果是,那就立马剪掉,否者的话,咱就不处理。

    相关文章

      网友评论

        本文标题:华为手机 Leak android.gestureboost.G

        本文链接:https://www.haomeiwen.com/subject/lpeqfxtx.html