Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 935
Erds Avatar asked Dec 18 '12 22:12

Erds


1 Answers

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).

like image 134
Thomas Keller Avatar answered Oct 20 '22 17:10

Thomas Keller