我有一个 Android 应用程序,正在尝试使用 dagger。我决定使用全局图形 + 活动图形。我有三个模块:
AndroidModule
活动模块
我不得不在
图表配置正确吗?我在
编辑:
像这样,Dagger没有错误,但如果我尝试注入一个
AndroidModule
@Module(library = true)
public class AndroidModule {
private final MApplication mApplication;
public AndroidModule(MyApplication application) {
mApplication = application;
}
@Provides @Singleton @ForApplication Context provideApplicationContext() {
return mApplication;
}
}
MyAppModules
@Module(
injects = {
MainActivity.class,
AddFragment.class,
AddMapFragment.class,
MyActivity.class,
ListFragment.class,
MyMapFragment.class,
RetainFragment.class,
SingleActivity.class,
UserActivity.class,
UserLoginFragment.class,
UserProfileActivity.class,
UserProfileFragment.class,
UserRegisterFragment.class,
WelcomeFragment.class
},
complete = false,
library = true,
includes = ActivityModule.class
)
public class MyAppModule {
private final Bus mBus = new Bus();
@Provides @Singleton Bus provideBus() {
return mBus;
}
@Provides @Singleton
RequestQueue provideRequestQueue(@ForApplication Context context) {
return Volley.newRequestQueue(context);
}
@Provides @Singleton Api provideApi(RequestQueue queue) {
return new AppApi(queue);
}
@Provides Logger provideLogger() {
return new MyLogger();
}
}
活动模块
@Module(
complete = false,
library = true
)
public class ActivityModule {
private BaseActivity mActivity;
public ActivityModule() {}
public ActivityModule(BaseActivity activity) {
mActivity = activity;
}
@Provides @Singleton @ForActivity Context provideActivityContext() {
return mActivity;
}
@Provides @Singleton LocationClientFactory provideLocationClientFactory() {
return new LocationClientFactory(mActivity);
}
}
我不得不在
MyAppModule
中使用include
来引用ActivityModule
,否则应用程序会崩溃,提示找不到Context
的构造函数,无法注入Activity
的Context
。图表配置正确吗?我在
Application
和BaseActivity
中将模块添加到了图表中,我认为这已经足够了,我不需要include
,但我不确定我完全理解此过程的配置。编辑:
像这样,Dagger没有错误,但如果我尝试注入一个
Activity
的Context
,在运行时它是null
。