2014-09-26 66 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對象需要一個上下文?

我沒有明白。