如何使用Dagger2提供上下文 [英] How to provide Context with Dagger2
问题描述
我正在学习Android,并且正在遵循有关RxJava和Dagger2的Retrofit2的指南. 现在,我不想处理没有互联网连接的情况. 我找到了这个答案, 看起来很优雅,但我不知道如何应用.
I am learning Android and I am following some guides for Retrofit2 with RxJava and Dagger2. Now I want to handle no internet connection case. I've found this answer, which seems to be elegant, but I do not understand how to apply it.
我有一些NetworkModule
,并带有OkHttpClient
提供程序.
我假设我需要使用拦截器创建OkHttpClient.Builder
.所以它应该看起来像这样:`
I've got some NetworkModule
, with OkHttpClient
provider.
I assume I need to create OkHttpClient.Builder
with interceptor. So it should look something like this: `
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
ConnectivityInterceptor ci = new ConnectivityInterceptor(networkObservable()));
OkHttpClient.Builder.addInterceptor(ci)
return builder.build();
}
private boolean networkObservable() {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
这没有用,因为我没有Context
.
我应该朝哪个方向去尝试在那儿获取上下文,或者我误解了可观察对象的概念?
This isn't working as I don't have Context
.
In which direction should I go - to try to obtain context there, or maybe I misunderstand the concept of observables?
推荐答案
您可以在DaggerModule中使用@Provides
批注来获取应用程序上下文.或者,您可以创建一个模块,该模块在其构造函数中接受Context参数,以防您需要活动上下文.然后,您可以在活动中构建组件并将参数注入其中.
You can use the @Provides
annotation in your DaggerModule to obtain application Context. Alternatively you can create a module which accepts a Context parameter in its constructor in case you need activity context. Then you can build the component in your activity and inject the arguments into it.
@Module
public class AppModule {
private Context context;
public AppModule(@NonNull Context context) {
this.context = context;
}
@Singleton
@Provides
@NonNull
public Context provideContext(){
return context;
}
}
应用程序类:
public class PFApplication extends Application {
private static AppComponent appComponent;
public static AppComponent getAppComponent() {
return appComponent;
}
@Override
public void onCreate() {
super.onCreate();
appComponent = buildComponent();
}
public AppComponent buildComponent(){
return DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
}
这篇关于如何使用Dagger2提供上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!