你如何实现DaggerService

Kel*_*Dev 5 android android-service dagger-2

我看过基础知识和课程,但是对匕首(甚至匕首2)不熟悉我不知道我怎么想用这个

这是匕首意图服务:https://google.github.io/dagger/api/latest/dagger/android/DaggerIntentService.html

我理解android意图服务和实现的基础知识,但我似乎无法找到DaggerIntentService的信息(我也很难找到DaggerService的信息)

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

谢谢,凯莉

baj*_*sko 6

这不是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);
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

记住你有root dagger组件,例如ApplicationComponent你在应用程序onCreate()方法中实例化的,你需要在你的应用程序类中有一个额外的公共方法.

ApplicationComponent

@Component(modules = ApplicationModule.class)
public interface ApplicationComponent{
    ServiceComponent.Builder serviceBuilder();
}
Run Code Online (Sandbox Code Playgroud)

ApplicationModule

@Module(subcomponents = ServiceComponent.class)
public class ApplicationModule{

    public ApplicationModule(MyApplication myApplication){
        this.myApplication = myApplication;
    }

    @Provides
    public MyApplication providesMyApplication(){
        return myApplication;
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

最后,你的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
    }
Run Code Online (Sandbox Code Playgroud)

一开始可能看起来很复杂,但是如果你已经设置了匕首结构,那么它只需要两到三个额外的类.

希望你觉得它有用.干杯.