首页 > 解决方案 > 通过 Dagger 2 注入 Leakcanary RefWatcher

问题描述

我想在我的活动和片段中获得 RefWatcher 对象,所以在我的主应用程序匕首模块中我做了

@Provides
@AppScope
static RefWatcher provideRefWatcher(Application application) {
    return ((AppName) application).refWatcher;
}

在我的应用程序类中我声明

public class AppName extends DaggerApplication {

public RefWatcher refWatcher;
...
}

但是,当我注入活动并用作

public class MainActivity extends DaggerAppCompatActivity {

@Inject
RefWatcher refWatcher;

@Override
public void onDestroy() {
    super.onDestroy();
    refWatcher.watch(this);
}

我收到错误

Caused by: java.lang.NullPointerException: Cannot return null from a non-@Nullable @Provides method

注入此泄漏 refwatcher 的正确方法是什么?

标签: androiddagger-2leakcanary

解决方案


因为 refWathcer 在这种情况下为空。试着得到它:

  @Override public void onCreate() {
    super.onCreate();
    refWatcher = LeakCanary.install(this);
  }

在您的应用程序类中。但通常在这种情况下使用匕首并不是一个好主意。安装 LeakCanary 后,您可以使用静态 LeakCanary.installedRefWatcher() 来获取 refWatcher 实例。


推荐阅读