问题
I need to access settings from various activities in my Android app. Rather than messing around with SharedPreferences in various activities I want to create a Singleton class, and grab all the settings at once using SharedPreferences in the Singleton. I also want a method in the Singleton to save settings where required, again using SharedPreferences.
The trouble with this is that I need an Activity context to use SharedPreferences. Could I pass this into the Singleton.. I've read about memory leaks and am wary of doing this.
Or am I completely barking up the wrong tree and is there a better way of sharing application settings between activities?
回答1:
As far as sharing information between Activities, you pretty much have two options:
- Singleton Class, like you suggested.
- Extend the
Application
class and store your information there (which to my limited knowledge, is some sort of buffed Singleton).
Personally I use Singletons to manage Application Scoped Information in my Android applications. I'd like to give you the pros and cons to both approach myself but it's been debated heavily all over the internet ;) This question answered all my question when I got into Android programming and was trying to figure out how to shared information in my application in the most intelligent way possible.
I, personally never had any problems passing my Context
to Singletons in order for them to do work related to Shared Preferences
. I guess you've just have to be careful about what you're doing, like anything you're coding really.
回答2:
You can try:
public class SomeApplication extends Application {
private static SomeApplication _instance;
public SomeApplication() {
super();
}
public static SomeApplication getInstance() {
return _instance;
}
@Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public SharedPreferences getPreferences() {
return getApplicationContext().getSharedPreferences( SOME_PREFS_KEY, Context.MODE_PRIVATE );
}
}
.....
SharedPreferences prefs = SomeApplication.getInstance().getPreferences();
.....
Don't forget about manifest.xml
<application android:label="@string/app_name" android:icon="@drawable/icon"
android:name="SomeApplication"
>
来源:https://stackoverflow.com/questions/9471645/android-using-singleton-to-access-hold-application-settings-and-context