【发布时间】:2018-01-19 16:44:54
【问题描述】:
我是 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);
}
}
应用组件
@Singleton @Component(modules = {AppModule.class})
public interface AppComponent
{
void inject (ApplicationClass applicationClass);
void inject (IntentService intentService);
void inject (Service service);
}
应用程序类
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 中注入共享首选项,并使用了这些代码行 在我的服务(intentservice)的 onCreate 方法中
@Inject
SharedPreferences preferences;
@Override
public void onCreate()
{
super.onCreate();
((ApplicationClass)getApplication()).getAppComponent().inject(this);
}
但问题是当我在onHandleIntent 方法中使用此首选项变量时,应用程序崩溃了,因为首选项为空。
那为什么不注入呢?
【问题讨论】:
-
你不必向 IntentService 注入上下文和共享首选项,IntentService 已经继承自 Context。您的问题是您应该在 AppComponent 中的目标类(在注入方法中)上使用名称,例如:
void inject (ApplicationClass applicationClass); void inject (CustomIntentService intentService); void inject (SimpleIntentService service); -
你需要指定一个具体的具体类而不是它的父类来注入。所以你不能只说
IntentService并注入任何意图服务,因为你的类不是IntentService,而是WhateverService。 -
@VadimKorzun 谢谢你可以看到我的意思是共享偏好并编辑了我的问题。感谢您澄清我的问题
-
@EpicPandaForce 也谢谢你!我认为如果我将 IntentService 作为参数传递给注入方法,我可以将此函数用于我的应用程序中从 IntentService 继承的所有类。谢谢:)
标签: android dependency-injection dagger-2