I have been using the dagger 2.11 AndroidInjection with no problems until i tried to Inject my Retrofit service in an OkHttp Authenticator in order to handle session timeouts.
AndroidInjection allows only for injections in Activities,Fragments,Services,ContentProviders and BroadcastReceicers.
My questions is how can i use the new Dagger AndroidInjection in a class that is not in the above list?
Just use inject to provide Retrofit, in the same module you provide also okhttp that is used by retrofit
@Singleton
@Provides
OkHttpClient providesOkHttpClient(){
return new OkHttpClient.Builder()
.connectTimeout(RETROFIT_API_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(RETROFIT_API_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(RETROFIT_API_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
}
@Singleton
@Provides
Retrofit providesRetrofit(OkHttpClient client){
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.build();
}
Then in your class:
public class MyClass {
Retrofit mRetrofit;
@Inject
public MyClass(Retrofit retrofit){
mRetrofit = retrofit;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.