Android application with RoboGuice 2.0 - How to insert a singleton with application context

I have a singleton GameStateManager that I want to have for all of my actions. In particular, I want him to listen for events triggered using the EventManager using the application context and not a separate activity context.

GameStateManager is tagged with singleton annotation

I tried to enter GameStateManager during Application.OnCreate (sorry, I typed the fragment from memory below, but was not copied and pasted, so it may be incorrect)

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

I thought that the GameStateManager instance would be built with the application context, and since it would be annotated since the singleton would be available later with the application context. I noticed that when I put the GameStateManager into action, I actually got a new singleton tied to the activity context. So basically I have 2 singleton :)

Any ideas on how to have a true "singleton" that is related to the application context?

Thanks!

+6
source share
2 answers

The problem you are observing may be caused by lazy initialization (see https://code.google.com/p/google-guice/wiki/Scopes ) in design mode.

If you first put your manager into action, he is being created lazily at that moment. Since Activity satisfies for any @Inject Context , this activity is introduced. This is actually very harmful, because if your manager annotates with @Singleton , it lives longer than activity, and you basically just created a memory leak.

I found it more explicit for @Inject Application or Activity depending on what I expected to inject where ( Activity usually for @ContextSingleton , Application for simple @Singleton ).

+1
source

Since RoboGuice is built under Guice , you can try using the @Singelton annotation, which guarantees one instance per Injector

Take a look at the sample application

0
source

All Articles