这不回答DaggerIntentService
问题,故意的。dagger.android
包或多或少地执行与您可以通过为 Intent 服务设置相关组件和模块手动执行的相同操作。所以你可以尝试以下方法:
ServiceComponent
@Subcomponent(modules = ServiceModule.class)
public interface ServiceComponent{
@Subcomponent.Builder
public interface Builder {
Builder withServiceModule(ServiceModule serviceModule);
ServiceComponent build();
}
void inject(MyService myService);
}
ServiceModule
@Module
public class ServiceModule{
private MyService myService;
public ServiceModule(MyService myService){
this.myService = myService;
}
@Provides public MyService provideServiceContext(){
return myService;
}
@Provides public SomeRepository provideSomeRepository(){
return new SomeRepository();
}
}
例如,请记住您有根匕首组件ApplicationComponent
您在应用程序中实例化的onCreate()
方法,您将需要在应用程序类中添加一个额外的公共方法。
ApplicationComponent
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{
ServiceComponent.Builder serviceBuilder();
}
ApplicationModule
@Module(subcomponents = ServiceComponent.class)
public class ApplicationModule{
public ApplicationModule(MyApplication myApplication){
this.myApplication = myApplication;
}
@Provides
public MyApplication providesMyApplication(){
return myApplication;
}
}
MyApplication
public class MyApplication extends Application{
ApplicationComponent applicationComponent;
@Override
public void onCreate(){
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
public ServiceComponent getServiceInjector(MyService myService){
return applicationComponent.serviceBuilder().withServiceModule(new ServiceModule(myService)).build();
}
最后,你的MyService
:)
MyService
public class MyService extends IntentService{
@Inject MyApplication application;
@Inject SomeRepository someRepository;
public onCreate(){
((MyApplication)getApplicationContext()).getServiceInjector(this).inject();
}
public void onHandleIntent(Intent intent){
//todo extract your data here
}
一开始它可能看起来很复杂,但如果您已经设置了匕首结构,那么它只需要两到三个额外的类。
希望您觉得它有帮助。
干杯。