我需要从我的 Android 应用中的各种 Activity 访问设置。我不想在各种 Activity 中弄乱 SharedPreferences,而是想创建一个 Singleton 类,并使用 Singleton 中的 SharedPreferences 一次获取所有设置。我还想要 Singleton 中的一种方法来在需要时保存设置,再次使用 SharedPreferences。
问题在于我需要一个 Activity 上下文才能使用 SharedPreferences。我可以将其传递给 Singleton 吗?我已经阅读了有关内存泄漏的信息,并且对此持谨慎态度。
或者我完全找错了树,有没有更好的方法在 Activity 之间共享应用程序设置?
最佳答案
你可以试试:
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();
.....
不要忘记 manifest.xml
<application android:label="@string/app_name" android:icon="@drawable/icon"
android:name="SomeApplication"
>
关于Android - 使用 Singleton 访问保留应用程序设置和 Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9471645/