gpt4 book ai didi

android - 你如何实现 DaggerService

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:36 26 4
gpt4 key购买 nike

我已经看过基础知识和类(class),但是作为 dagger(甚至是 dagger 2)的新手,我不知道我应该如何使用它

这是 Dagger Intent 服务:https://google.github.io/dagger/api/latest/dagger/android/DaggerIntentService.html

我了解 android Intent 服务和实现的基础知识,但我似乎无法通过 DaggerIntentService 找到信息(而且我也很难找到 DaggerService 的信息)

我的目标是使用 TDD 构建它,但我真的只需要了解实现基于 Dagger 的服务的工作流程

谢谢,凯利

最佳答案

这并没有故意回答 DaggerIntentService 问题。 dagger.android 包或多或少地做同样的事情,你可以通过为 Intent 服务设置相关的组件和模块来手动完成。所以你可以尝试以下方法:

服务组件

@Subcomponent(modules = ServiceModule.class)
public interface ServiceComponent{

@Subcomponent.Builder
public interface Builder {
Builder withServiceModule(ServiceModule serviceModule);
ServiceComponent build();
}

void inject(MyService myService);
}

服务模块

@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();
}
}

考虑到您有根 Dagger 组件,例如您在应用程序 onCreate() 方法中实例化的 ApplicationComponent,您将需要一个额外的公共(public)方法应用类。

应用组件

@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{
ServiceComponent.Builder serviceBuilder();
}

应用模块

@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 :)

我的服务

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
}

乍一看可能看起来很复杂,但如果您已经设置了 Dagger 结构,那么它只需要两到三个额外的类。

希望对您有所帮助。干杯。

关于android - 你如何实现 DaggerService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45341072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com