【问题标题】:Why Memory Leak is not detected with LeakCanary while HPROF file displays activites with leaks为什么 LeakCanary 未检测到内存泄漏,而 HPROF 文件显示有泄漏的活动
【发布时间】:2018-03-30 08:04:25
【问题描述】:

我认为 FusedLocationProvider api 的代码泄漏了,正如我在 question 中所问的那样。我尝试使用 LeakCanary 检测内存泄漏,但在旋转手机后我没有收到任何内存泄漏警告,也尝试使用平板电脑。设置 LeakCanary 的代码:

public class MyApplication extends Application {
    private RefWatcher refWatcher;
    @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        refWatcher = LeakCanary.install(this);
        // Normal app init code...
        Log.d("TAG", "MyApplication onCreate()");
    }
}

我尝试了 20 多次,但有 2 次我从 LeakCanary 收到通知,甚至没有旋转手机,但在设备旋转后应该会发生内存泄漏。

我还有另一个问题,为什么即使没有发生内存泄漏并且不存在对这些 MainActivity 的引用,也会创建新的 MainActivity 实例。

设备旋转 2 次而不开始位置更新:

开始位置更新后设备旋转 2 次:

如果使用stopLocationUpdates() 方法停止位置更新onPause(),为什么会发生内存泄漏?

为什么 LeakCanary 没有检测到这些泄漏?

【问题讨论】:

    标签: android memory-leaks fusedlocationproviderapi leakcanary


    【解决方案1】:

    您不需要为 RefWatcher 创建变量。

    你可以试试这个:

     @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        // Normal app init code...
    }
    

    还要确保你的 gradle 中有这些。

      debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
      releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
     //Optional, if you use support library fragments:
     debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.3'
     testImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.3'
    

    【讨论】:

      【解决方案2】:

      您应该再次运行您的应用程序。因为我们第一次启动调试版本时,canaryleak 没有识别出泄漏。但关闭应用程序并再次运行它会识别泄漏(但请确保在出现弹出窗口时给予 canaryleak 所需的权限)。 祝你好运

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 2012-01-22
        相关资源
        最近更新 更多