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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With