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!

Erds
  • 513
  • 5
  • 16

2 Answers2

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

Thomas Keller
  • 5,933
  • 6
  • 48
  • 80
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

Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
  • 1
    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 well – Erds Dec 21 '12 at 15:54
  • The javadoc says it should be singelton for context. Going to search more. So let delete this answer so far. – Eugen Martynov Dec 21 '12 at 16:00
  • feel free to delete, I don't have that option – Erds Dec 21 '12 at 18:38
  • That is what I tried (using @Singleton). Maybe I don't understand what the "per Injector" means in an Android app. – Erds Jan 03 '13 at 18:09