android如何编写service,android-如何实现DaggerService

这没有故意地回答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,在您的应用程序类中将需要其他公共方法.

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;

}

}

我的应用程序

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

}

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

希望对您有所帮助.

干杯.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值