我在项目中使用Roboguice进行DI。根据android文档,只能存在一个应用程序实例。但是操作系统和Roboguice创建的实例是不同的。
如何强制Roboguice注入由OS创建的应用程序并禁用新实例的创建?
一些代码说明了下面的情况
public class MyApplication extends Application {
public static MyApplication getInstance() {
if (instance == null) {
throw new IllegalStateException("Application isn't initialized yet!");
}
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
public class MyActivity extends RoboActivity {
// roboApp and osApp two different objects but expected that roboApp the same as osApp
@Inject
private MyApplication roboApp;
private MyApplication osApp = MyApplication.getInstance();
}
答案 0 :(得分:1)
RoboGuice不会致电MyApplication.getInstance()
,而是致电new MyApplication()
您可以编写一个调用MyApplication.getInstance()
的提供程序。这看起来像是:
public MyAppProvider implements Provider<MyApplication> {
@Override
public MyApplication get() {
return MyApplication.getInstance();
}
}
然后,您可以在模块中将其绑定为:bind(MyApplication.class).toProvider(MyAppProvider.class);