【发布时间】:2014-09-26 08:11:59
【问题描述】:
我想知道 Roboguice 注入了哪个上下文,是应用程序上下文还是当前活动?
我正在尝试同时使用 Roboguice 和 Robospice。我在片段中注入 Robospice 的 SpiceManager,但片段不知道 SpiceManager,它通过一个接口看到它,比如说 MyInterface。
public class MyFragment extends RoboFragment {
//this is where the SpiceManager gets injected
@Inject MyInterface manager;
...
}
//this is the implementation that I'm going to inject
//it is simultaneously an event listener for the fragment's life cycle events so that the
//SpiceManager can be appropriately started and stopped.
public class MyManager implements MyInterface {
private SpiceManager spiceManager = new SpiceManager(MySpiceService.class);
//Which context will get injected here? How can I make Roboguice inject a specific context that I want, for example, a specific activity that I want.
private @Inject Context context;
//Here, I need to start the SpiceManager
public void myFragmentOnStart(@Observes OnStartEvent onStart) {
//SpiceManager requires a context, more specifically an activity which will be destroyed and then garbage collected, so It shouldn't be an application context because the resources SpiceManager uses will never be released.
spiceManager.start(context);
}
public void myFragmentOnStop(@Observes OnStopEvent onStop){
if (spiceManager.isStarted()) {
spiceManager.shouldStop();
}
}
}
我的问题是:
RoboGuice能否在Activity事件旁边观察片段事件,文档不清楚?
我认为 SpiceManager 需要一个在片段/活动被销毁时将被销毁的上下文是否正确?我查看了SpiceManager.start(Context context) 的代码,它为传递的Context 创建了一个WeakReference。
如何让 RoboGuice 注入特定的Context/Activity?
如果MyFragment 不知道它使用的MyInterface 对象需要Context,是否可以这样做?
顺便我发现OnStopEvent有一个getActivity()方法,所以在onStop中获取Activity是没有问题的,但是OnStartEvent只是一个空类。
【问题讨论】:
标签: android roboguice robospice