【问题标题】:Which context is injected by roboguice?roboguice 注入了哪个上下文?
【发布时间】: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


    【解决方案1】:

    这么多问题;)

    A) RoboGuice 能否在 Activity 事件旁边观察片段事件,文档不清楚?

    事件可以是 RG 中的任何东西。默认情况下,RG 提供了一些很好的事件来通知活动的生命周期。 RG 3.1 版实际上是为 Fragments 添加了一些新事件。这应该会在几周内发布。

    但是您在活动方面所做的事情是完全合法的。只是要清楚。您正在从片段中收听活动生命周期。为什么不呢?

    您唯一需要做的就是注册到该活动的事件管理器实例。将@Inject EventManager eventManager 添加到您的片段中。这足以让 RG 自动注册您的侦听器。

    B) RS 只需要一个用于回调的上下文,而不是执行请求。该请求将在服务中执行。你传递给 RS 的上下文只是用来说“如果这个上下文死了,那么所有的监听器都会死,不要通知他们。但是,继续,执行请求并缓存结果。”

    这里的操作方式有点复杂。最简单的实际上是在活动级别管理香料经理。将片段中的事件发送到您的活动,以要求它在需要时启动请求。那是最简单的。

    但也可以在片段级别管理 spicemanager。在这种情况下,请使用其 onStart/onStop 方法在片段本身中管理您的 spicemanager 生命周期。

    C) 是否可以在 MyFragment 不知道它使用的 MyInterface 对象需要 Context 的情况下这样做?

    我没听懂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多