作者:心有阳光2502937567_240 | 来源:互联网 | 2023-02-06 09:35
我已经看过基础知识和类,但是对Dagger(甚至Dagger2)是陌生的,我不知道该如何使用它这是匕首意图服务:https:google.github.iodaggerapilat
我已经看过基础知识和类,但是对Dagger(甚至Dagger 2)是陌生的,我不知道该如何使用它
这是匕首意图服务:https://google.github.io/dagger/api/latest/dagger/android/DaggerIntentService.html
我了解android意图服务和实现的基础知识,但是我似乎无法在DaggerIntentService上找到信息(而且我也很难为DaggerService找到信息)
我的目标是使用TDD进行构建,但实际上我只需要了解实现基于Dagger的服务的工作流程
谢谢,
黄绿色
解决方法:
这没有故意地回答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