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.gradle
Then make sure you app component inherit from
AndroidInjector
ActivityBuilderModule
andServiceBuilderModule
reference all you activitiy and service subcomponents using an handy annotationContributesAndroidInjector
that will generate the subcomponent automatically for yousame for services
Finally here how your
MyApp
should look likeYour service should now be injectable, to wrap this up you'll certainly want to inject fragments as well so for example for
MainActivity
fragments you'll make aFragmentBuilderModule
from yourMainActivityModule
and here the
FragmentBuilderModule
classYou can see more from my project template here though it's kotlin.