I am trying to use the last version to date (3.0.1) of RoboGuice on my new Android application using Android Studio 1.5 (stable).
Long ago, I dealt with Guice & RoboGuice but I took on some reading on how to use Roboguice with new improvements & features it got since.
The point here is that I want to use a custom module for custom bindings.
In my specific case I have a SoundManager class that provides tools to play multiple audio tracks at will with an internal pool of MediaPlayer. The main constructor takes the applicationContext that will be used to create new MediaPlayer. Furthermore this class ought to be a singleton :
- If a track is to be played throughout the entire application, the
SoundManagercannot be destroyed / recreated ; - One pool of
MediaPlayeris enough, much like aExecutorPool. It ought to be re-used whenever necessary for better resources management.
So I did the following :
- Creating an interface exposing the default behavior of my
SoundManager: play, stop, resume, release etc... ; - Implementing this interface in a fully working class ;
- Creating a
Moduleextendingcom.google.inject.AbstractModulewith the following code :
@Override protected void configure() { bind(SoundManagerInterface.class).to(SoundManager.class).asEagerSingleton(); }
Now the whole point of this SO post :
where did RoboGuice.setBaseApplicationInjector() go ?? All articles I read with modules examples, the most recent as early as 2014, expose the same method : creating an Application class extending android.app.Application and in the onCreate() method, use RoboGuice.setBaseApplicationInjector(). But it does not exist ! The only available methods I have are :
RoboGuice.getOrCreateBaseApplicationInjector()RoboGuice.destroyInjector()RoboGuice.newDefaultRoboModule()RoboGuice.overrideApplicationInjector()RoboGuice.setUseAnnotationDatabases()RoboGuice.injectMembers()
In my case I used getOrCreateBaseApplicationInjector() because it seemed to be the closest to setBaseApplicationInjector() and finally went on testing my code.
Suprise, it worked ! My SoundManager is properly created and the applicationContext is somehow injected (from where, I do not know, but I hope it's not the calling Activity or else I am done for leaking memory...) and audio tracks are indeed played.
But is the instance of my SoundManager that of a singleton ? No it is not. I tried injecting 3 of those and there are all differents object as the debugger is showing...
So what am I doing wrong ?
This link : https://github.com/roboguice/roboguice/wiki/Advanced-Custom-Bindings#register-the-module-with-roboguice cannot be reproduced in my code :/
The correct setup code is as per the wiki :
From your use case (persistence throughout the entire activity, start/stop etc), it sounds like you want to create a
RoboServiceand inject theSoundManagerinto that. Please see the documentation on Services. Merely creating aSingletonwill not allow you to completely avoid standard Android architecture patterns.