我很难弄清楚如何将CachedRithms
注入我的RithmioManager
和CachedKamms
进入我的KamilManager
?
我有以下文件:
AppScopeModule:
@Module
(
library = true,
complete = false,
injects = {
KamilApplication.class,
KamilManager.class
}
)
public class AppScopeModule {
/* package */ static Context sApplicationContext = null;
private final Context mApplicationContext;
AppScopeModule(Context applicationContext) {
KamilManager.initInstance(applicationContext);
mApplicationContext = applicationContext;
}
@Provides
@Singleton
KamilManager provideKamilManager() {
return KamilManager.getInstance();
}
}
KamilApplication:
public class KamilApplication extends Application implements Injector {
private ObjectGraph mObjectGraph;
@Inject
KamilManager KamilManager;
@Override
public void onCreate() {
super.onCreate();
AppScopeModule sharedAppModule = new AppScopeModule(this);
// bootstrap. So that it allows no-arg constructor in AppScopeModule
sharedAppModule.sApplicationContext = this.getApplicationContext();
List<Object> modules = new ArrayList<Object>();
modules.add(sharedAppModule);
modules.add(new AuthModule());
modules.addAll(getAppModules());
mObjectGraph = ObjectGraph.create(modules.toArray());
mObjectGraph.inject(this);
}
}
KamilManager
public class KamilManager {
@Inject
CachedKamms mCachedKamms;
private static KamilManager instance;
private boolean mWearIsConnectedToMobile;
private KamilManager() {
Log.d(TAG, "KamilManager private constructor");
}
public static void initInstance(Context appContext) {
if (instance == null) {
instance = new KamilManager();
.....doing more things here...
}
}
public static KamilManager getInstance() {
return instance;
}
}
但是,当我初始化应用时,mCAchedKamms
始终为空。知道我做错了吗?
答案 0 :(得分:1)
您需要在ObjectGraph.inject(this)
中的某个地方拨打KamilManager
。
我建议您将此代码添加到您的KamilApplication类中:
public ObjectGraph getObjectGraph() {
return mObjectGraph;
}
之后你需要在KamilApplication
中以某种方式获取KamilManager
的实例(通过构造函数传递它?)并调用:
kamilApplication.getObjectGraph.inject(this);
此调用后,应注入注释为KamilManager
的班级@Inject
中的每个字段。
使用CachedKamms
@Inject
的构造函数
除非您知道自己在做什么,否则请避免使用library = true
和complete = false
。使用此设置可在编译时禁用某些验证。