我看过基础知识和课程,但是对匕首(甚至是匕首2)不熟悉我不知道我怎么想用这个
这是匕首意向服务:https://google.github.io/dagger/api/latest/dagger/android/DaggerIntentService.html
我理解android意图服务和实现的基础知识,但我似乎无法找到DaggerIntentService的信息(我也很难找到DaggerService的信息)
我的目标是使用TDD构建它,但我真的只需要了解实现基于匕首的服务的工作流程
谢谢, 凯利
答案 0 :(得分:5)
这不会故意回答DaggerIntentService
问题。通过为Intent服务设置相关的组件和模块,dagger.android
个包或多或少可以手动执行相同的操作。所以你可以尝试以下方法:
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();
}
}
考虑到你有root dagger组件,例如你在应用程序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
}
一开始可能看起来很复杂,但是如果你已经设置了匕首结构,那么它只需要两到三个额外的类。
希望你觉得它有用。 欢呼声。