What's the best way to inject dependencies in a scheduled jobservice in Android. My JobService is scheduled to run in the night to do some stuff.
In JobService constructor i'm trying to inject my dependencies over my Application class.
MyApp.component().inject(this);
But sometimes MyApp isn't initialized at this time and so the injection failes.
Maybe i'm using Dagger in a wrong way? Or do i have to create an own component for the JobService?
Here is my Application class
public class MyApp extends Application {
private static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
buildAppComponent();
}
public static AppComponent component(){
return appComponent;
}
private void buildAppComponent(){
if(appComponent == null){
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
}
}
You should use AndroidInjector to inject android classes such as Activities/Fragments/Services/BroadcastReceivers/ContentProviders.
First make sure you added dagger-android dependency from your
build.gradleThen make sure you app component inherit from
AndroidInjectorActivityBuilderModuleandServiceBuilderModulereference all you activitiy and service subcomponents using an handy annotationContributesAndroidInjectorthat will generate the subcomponent automatically for yousame for services
Finally here how your
MyAppshould look likeYour service should now be injectable, to wrap this up you'll certainly want to inject fragments as well so for example for
MainActivityfragments you'll make aFragmentBuilderModulefrom yourMainActivityModuleand here the
FragmentBuilderModuleclassYou can see more from my project template here though it's kotlin.