你如何实现 DaggerService

How do you implement DaggerService

我已经了解了基础知识以及 class,但是作为 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,您需要在应用程序中添加一个额外的 public 方法 class.

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
    }

乍一看可能看起来很复杂,但如果您已经设置了匕首结构,那么只需再增加两到三个 classes。

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