我是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