这没有故意地回答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();
}
}
请记住,您具有根匕首组件,例如您在应用程序的onCreate()方法中实例化的ApplicationComponent,在您的应用程序类中将需要其他公共方法.
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;
}
}
我的应用程序
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
}
乍一看它可能看起来很复杂,但是如果您已经设置了匕首结构,那么只需增加两到三个类.
希望对您有所帮助.
干杯.