我想在我的活动和片段中让 RefWatcher 对象可用,所以在我的主应用程序dagger模块中我做了
@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
注入此泄漏金丝雀引用观察器的正确方法是什么?
因为 refWathcer 在这种情况下是空的。尝试让它像:
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
在您的应用程序类中。但一般来说,在这种情况下使用dagger不是一个好主意。安装 LeakCanary 后,您可以使用静态 LeakCanary.installedRefWatcher(( 来获取 refWatcher 实例。