Using Dagger 2 to inject into service

北慕城南 提交于 2019-11-30 00:43:50

I wrote the code from the top of my head, so there could be a typo or two.

You do it just the same as when injecting stuff into activities.

  1. Declare a component,
  2. add the inject method to that component,
  3. add a module providing your service
  4. create that components builder
  5. add your module to the builder
  6. inject your service with the component

Your module and component would look something like this (maybe add some scope)

@Module
class ServiceModule {

    MyService mService;

    ServiceModule(MyService service) {
        mService = service;
    }

    @Provides
    MyService provideMyService() {
        return mService;
    }
}

@Component(modules=ServiceModule.class)
interface MyServiceComponent {
    void inject(MyService service);
}

Then in onCreate just create your component and inject your alarm.

@Inject
private SomeAlarm alarm;

public void onCreate() {
    DaggerMyServiceComponent.builder()
            .serviceModule(new ServiceModule(this))
            .build()
            .inject(this);

    alarm.doStuff();
}

This is assuming that your alarm can be constructor injected by having an @Inject annotated constructor like this:

class SomeAlarm {
    @Inject
    SomeAlarm(MyService service) {
        /*constructor stuff*/
    }
}

Else you would just also add the alarm creation to your module.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!