Android内存优化之LeakCanary

LeakCanary是检查内存泄漏的神器

虽然我没检查出来啥内存泄漏

是我代码写的ok还是我的打开方式不正确?

不管怎么说

在app上线前检查一下内存泄漏

是必要的工作


学习自

https://blog.csdn.net/itachi85/article/details/77826112?utm_source=gold_browser_extension


依赖

 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.4'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
 }

Application中

public class LeakApplication extends Application {
    private RefWatcher refWatcher;
    @Override
    public void onCreate() {
        super.onCreate();
        refWatcher= setupLeakCanary();
    }
    private RefWatcher setupLeakCanary() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return RefWatcher.DISABLED;
        }
        return LeakCanary.install(this);
    }

    public static RefWatcher getRefWatcher(Context context) {
        LeakApplication leakApplication = (LeakApplication) context.getApplicationContext();
        return leakApplication.refWatcher;
    }
}

检测

RefWatcher refWatcher = LeakApplication.getRefWatcher(this);//1
refWatcher.watch(this);

活动中一般在他onDestory方法里写这个,另外的Java类也可以在任意时机进行监听


注意点

1.release版本是无效的

2.进入app后稍微运行运行,有内存泄漏后,图标就出来了(如果没有内存泄漏,可以制造一个出来)

猜你喜欢

转载自blog.csdn.net/qq_36523667/article/details/80167371