我是Dagger2的新手,我試圖在應用程序中使用依賴注入。 我正在使用共享首選項,並認爲使用依賴注入將更有幫助,而不是每次需要使用它時都會獲得共享特權的實例。 當我在活動和片段上使用它時,它工作正常,但當我嘗試在服務或intentservice上使用它時,它無法正常工作。Android Dagger2依賴注入
這裏是我的代碼:
的AppModule:
@Module
public class AppModule
{
public final ApplicationClass application;
public AppModule(ApplicationClass application)
{
this.application = application;
}
@Provides @Singleton
Context providesApplicationContext()
{
return this.application;
}
@Provides @Singleton
SharedPreferences providesSharedPreferences()
{
return application.getSharedPreferences(Constants.FILE_NAME,Context.MODE_PRIVATE);
}
}
AppComponent
@Singleton @Component(modules = {AppModule.class})
public interface AppComponent
{
void inject (ApplicationClass applicationClass);
void inject (IntentService intentService);
void inject (Service service);
}
ApplicationClass
public class ApplicationClass extends Application
{
AppComponent appComponent;
@Override
public void onCreate()
{
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
onUncaughtException(t, e);
}
});
appComponent = DaggerAppComponent
.builder()
.appModule(new AppModule(this))
.build();
appComponent.inject(this);
}
public AppComponent getAppComponent()
{
return this.appComponent;
}
private void onUncaughtException(Thread t, Throwable e)
{
e.printStackTrace();
Intent crash= new Intent(getApplicationContext(),Crash.class);
about.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(crash);
}
}
於是,我就注入在IntentService共享的喜好和我用我的服務的onCreate方法(intentservice)
@Inject
SharedPreferences preferences;
@Override
public void onCreate()
{
super.onCreate();
((ApplicationClass)getApplication()).getAppComponent().inject(this);
}
裏面的代碼 這些線,但問題是,當我使用這個喜好在onHandleIntent
方法中變量,應用程序崩潰,因爲首選項爲空。 那麼,爲什麼它不注入?
你不必注入上下文和共享偏好來IntentService,IntentService已經從上下文中繼承。你的問題是你應該在AppComponent的目標類(注入方法)上使用名稱來檢查:'void inject(ApplicationClass applicationClass); void inject(CustomIntentService intentService); 無效注射(SimpleIntentService服務)' – Onregs
你需要指定一個特定的**具體類**,而不是它的父類,在其中注入。所以你不能只說'IntentService'並注入任何意圖服務,它將是空的,因爲你的類不是'IntentService',它是'WhateverService'。 – EpicPandaForce
@VadimKorzun非常感謝,你可以看到我的意思是共享偏好並編輯了我的問題。 感謝您澄清我的問題 – Elior