Android - 使用 Singleton 访问保留应用程序设置和 Context

标签 android singleton sharedpreferences android-context

我需要从我的 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/

相关文章:

android - 我如何在全屏中滑动选定的网格图像

java - 如何将 RecyclerView 所有元素的背景更改为 SharedPreferences 保存的颜色?

java - 自定义 SharedPreferences 类

java - 如何注册方向变化的监听器?

java - RecyclerAdapter getItemCount 崩溃

android - Firebase isSuccessful() 总是返回 false

ios - 如何使我的单例类可扩展?

java - java中的单例

java - 如何从对象中查找类是否为单例类?

flutter - 在Flutter中关闭应用程序时如何保存数据