Android app with RoboGuice 2.0 - How to inject a Singleton with the Application context
Asked Answered
R

2

6

I have a GameStateManager singleton that I want to have available to all of my activities. In particular I want it to listen for Events fired off with the EventManager using the Application Context instead of an individual Activity Context.

GameStateManager is marked with the singleton annotation

I tried to inject GameStateManager during Application.OnCreate (sorry, typed the below snippet from memory, not copied and pasted, so might be incorrect)

public void OnCreate(){
    GameStateManager gameStateManager = RoboGuice.InjectMembers(this.getApplicationContext(), new GameStateManager())

}

I thought that the instance of GameStateManager would be constructed with the application context and since it is annotated as a singleton would therefore be available later with the application context. What I noticed was that when I injected the GameStateManager into an activity, I actually got a new singleton tied to the activity context. So in essence I have 2 singletons :)

Any ideas on how to have a true 'singleton' that is connected to the Application context?

Thanks!

Rancourt answered 18/12, 2012 at 22:6 Comment(0)
O
1

The issue you observe could be caused by lazy initialization (see https://code.google.com/p/google-guice/wiki/Scopes) in the development mode.

If you inject your manager at first in an activity, it is created lazily at that point. Since Activity satisfies for any @Inject Context, the activity is injected. This is actually very harmful, because if your manager is annotated with @Singleton, it lives longer than the activity and you basically just created a memory leak.

I found it more explicit to @Inject Application or Activity depending on what I expected to be injected where (Activity usually for @ContextSingleton's, Application for plain @Singleton's).

Overheat answered 9/10, 2013 at 8:30 Comment(0)
A
0

Since RoboGuice is built under Guice you could try to use @Singelton annotation which guarantee one instance per Injector

Take a look to example application

Albatross answered 21/12, 2012 at 12:30 Comment(4)
I tried that, and it didn't work. If I'm not mistaken, doesn't the ContextSingleton give you a singleton per context, which is actually the experience I am seeing with the Singleton as wellRancourt
The javadoc says it should be singelton for context. Going to search more. So let delete this answer so far.Albatross
feel free to delete, I don't have that optionRancourt
That is what I tried (using @Singleton). Maybe I don't understand what the "per Injector" means in an Android app.Rancourt

© 2022 - 2024 — McMap. All rights reserved.