2014-09-26 25 views
1

我想知道Roboguice注入的是哪种上下文,是应用程序上下文还是当前活动?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观察活动事件旁片段事件,文件是不是清楚了吗?

我是否认为SpiceManager需要一个当片段/活动被销毁时会被销毁的上下文?我看了一下SpiceManager.start(Context context)的代码,它创建了一个WeakReferenceContext

我该如何让RoboGuice注入特定的Context/Activity

是否有可能这样做,而没有MyFragment知道它使用的MyInterface对象需要Context

通过我发现OnStopEventgetActivity()方法,所以没有问题越来越在onStopActivity,但OnStartEvent只是一个空类的方式。

回答

1

这么多的问题;)

A)RoboGuice可以观察活动事件旁片段事件,文件是不是清楚了吗?

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

但是你在事件方面做的事情是完全合法的。只是要清楚。您正在监听片段内的活动生命周期。为什么不 ?

您唯一需要注册的是该活动的活动管理器的实例。将@Inject EventManager eventManager添加到您的片段。这足以让RG自动注册您的监听器。 B)RS只需要一个上下文而不是执行请求。该请求将在服务中执行。你传递给RS的上下文只是用来说“如果这个上下文死了,那么所有的听众都会死,不会通知他们,但是仍然继续,执行请求并缓存结果。”

这样做的方式有点复杂。最简单的就是在活动层面管理一名香料经理。将片段中的事件发送到您的活动,以便在需要时请求它启动请求。这是最简单的。

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

C)有没有可能这样做,没有MyFragment知道它使用的MyInterface对象需要一个上下文?

我没有明白。