问题
I need to make one instance of some class - and this one instance need to be accessible from any place in the code.
So, I found the Guice... and i want to use the '@Singleton' from this package but i don't find any example or some doc to how to use it and how to make the declaration.
回答1:
Ok, My answer is not a specific for @Singleton of Guice, But If you want to Make a class which is accessible through all your activities then I think,You have to use Application class of Android. (This is my personal opinion for your need)
The way to do this is to create your own subclass of android.app.Application
, and then specify that class in the application tag in your manifest. Now Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext()
method (Activity also provides a method getApplication()
which has the exact same effect):
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
This has essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android framework. Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
Here is the nice tutorial about how to use it, Extending the Android Application class and dealing with Singleton
回答2:
@Singleton is very easy to use. It just goes like this
@Singleton
public class A {
@Inject
public A() {
}
}
Please note however that the singleton is one per injector and not per VM. Singleton is a scope type and GUICE also allows custom scopes which can be very useful. Please see links below.
When you use this in another class you just need to inject it.
public class B {
@Inject
public B(A a) {
}
}
http://code.google.com/p/google-guice/wiki/Scopes
http://code.google.com/p/google-guice/wiki/GettingStarted
回答3:
public class DestinationViewManger {
private static final DestinationViewManger instance = new DestinationViewManger();
public Boolean flag=false;
// Private constructor prevents instantiation from other classes
private DestinationViewManger(){ }
public static DestinationViewManger getInstance() {
return instance;
}
}
//try this singleton class once. no need for getter and setter method
DestinationViewManger dstv;
dstv=DestinationViewManger.getInstance();
dstv.flag=true; //set the value for your flag
boolean whatFlagboo=dstv.flag; //get your flag wherever you want
来源:https://stackoverflow.com/questions/8489239/how-to-use-singleton-of-guice