How do you implement DaggerService

此生再无相见时 提交于 2019-12-01 17:47:52
bajicdusko

This does not answer the DaggerIntentService problem, on purpose. dagger.android packages more or less do the same thing you can do manually by setting relevant component and module for the Intent service. So you might try following approach:

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

Having in mind that you have root dagger component, for example ApplicationComponent which you instantiate in application onCreate() method, you'll need an additional public method in your application 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();
}

Finally, your 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
    }

It might look complicated at first, but if you have dagger structure setup already, then its just two to three additional classes.

Hope you find it helpful. Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!