KellyTheDev KellyTheDev - 2 years ago 190
Android Question

How do you implement DaggerService

I've looked at the basics as well as the class, but being new to dagger (or even dagger 2) I have no idea how I'm suppose to use this

Here is the dagger intent service:

I understand the android intent service and the basics for implementing, but I can't seem to find info over the DaggerIntentService (and I also struggle at finding info for DaggerService)

My goal is to build it using TDD, but I really just need to understand the workflow for implementing a dagger based service


Answer Source

This does not answer the DaggerIntentService problem, on purpose. packages more or less do the same thing you can do manually by setting relevant component and module for the Intent service. So you might try following approach:


@Subcomponent(modules = ServiceModule.class)
public interface ServiceComponent{

    public interface Builder {
        Builder withServiceModule(ServiceModule serviceModule);
        ServiceComponent build();

    void inject(MyService myService);


public class ServiceModule{

    private MyService myService;

    public ServiceModule(MyService myService){
        this.myService = myService;

    @Provides public Context provideServiceContext(){
        return myService;

    @Provides public SomeRepository provideSomeRepository(){
        return new SomeRepository();

Having in mind that you have root dagger component, for example ApplicationComponent which you instantiate in application onCreate() method, you'll need an additional public method in your application class.


@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{
    ServiceComponent.Builder serviceBuilder();


@Module(subcomponents = ServiceComponent.class)
public class ApplicationModule{

    public ApplicationModule(MyApplication myApplication){
        this.myApplication = myApplication;

    public MyApplication providesMyApplication(){
        return myApplication;


public class MyApplication extends Application{

    ApplicationComponent applicationComponent;

    public void onCreate(){
        applicationComponent = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))

    public ServiceComponent getServiceInjector(MyService myService){
        return applicationComponent.serviceBuilder().withServiceModule(new ServiceModule(myService)).build();

Finally, your MyService :)


public class MyService extends IntentService{

    @Inject MyApplication application;
    @Inject SomeRepository someRepository;

    public onCreate(){

    public void onHandleIntent(Intent intent){
        //todo extract your data here

It might look complicated at first, but if you have dagger structure setup already, then its just two to three additional classes.

Hope you find it helpful. Cheers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download