這不回答這個問題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();
}
}
銘記你有根匕首組件,例如ApplicationComponent
,你」你實例化應用onCreate()
方法在你的應用程序類中需要額外的公共方法。
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
}
它看起來複雜在第一,但如果你有匕首結構設置好的,那麼它只有兩三個額外的類。
希望你覺得它有幫助。 乾杯。
感謝分解@bajicdusko,我仍然有點失落。 1.你的服務是從Service而不是DaggerService或DaggerIntentService實現的,那麼這個實現又有什麼不同? 2.如果注入流程與使用DaggerService相同,那麼爲什麼不做構造函數注入? – KellyTheDev
@KellyTheDev上面的實現不使用DaggerService,也不使用DaggerIntentService。這兩個類是dagger.android的一部分,不在上面使用。我們上面做的幾乎與這兩個類所做的相同,但手動顯示工作流。 關於注入,我希望我明白你的問題 - >服務不能使用構造函數注入,因爲你不會通過它的構造函數實例化服務。即使在DaggerService類中,描述也指出「在onCreate()中注入其成員的服務」。你可以使用const。但是從上面注入SomeRepository。 – bajicdusko
好吧,我認爲我在這個@bajicdusko上與你同在(再次感謝BTW)。因此,上面的所有內容都是手動的,說我需要1.實現DaggerIntentService 2.執行屬性注入,如@Inject SomeRepository someRepository;(它在onCreate()中注入/連接)。 3A。如果我需要一個特定的ApplicationClass ref,請重寫onCreate方法,如上所示。 4.用onHandleIntent()做東西() – KellyTheDev