java 有没有办法在我的整个 Android 应用程序中使 SharedPreferences 全局化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11552579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:32:06  来源:igfitidea点击:

Is there a way to make SharedPreferences global throughout my whole Android app?

javaandroidandroid-preferences

提问by Ethan Allen

Is there a way to make SharedPreferences global throughout my whole app? Right now I'm using these lines in a lot of places throughout my code to store simple on/off settings for a number of preferences that my users can set. I just want to call them once globally if possible:

有没有办法让 SharedPreferences 在我的整个应用程序中全局化?现在,我在整个代码的很多地方都使用这些行来存储用户可以设置的许多首选项的简单开/关设置。如果可能,我只想在全局范围内调用它们一次:

SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();

Any tips on how to be able to call just these line in all classes would be awesome:

关于如何在所有类中只调用这些行的任何提示都会很棒:

editor.putString("examplesetting", "off");
editor.commit(); 

and

String checkedSetting = settings.getString("examplesetting", "");

回答by t0mm13b

I know, I know, I will get inflamed, and casted into the embers of hell....

我知道,我知道,我会发炎,然后被扔进地狱的余烬中……

Use a singleton class that wraps around the SharedPreferencesettings.. something like this:

使用环绕SharedPreference设置的单例类.. 像这样:

public class PrefSingleton{
   private static PrefSingleton mInstance;
   private Context mContext;
   //
   private SharedPreferences mMyPreferences;

   private PrefSingleton(){ }

   public static PrefSingleton getInstance(){
       if (mInstance == null) mInstance = new PrefSingleton();
       return mInstance;
   }

   public void Initialize(Context ctxt){
       mContext = ctxt;
       //
       mMyPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
   }
}

And create wrapper functions around what your examples represented in the question, for example,

并围绕您的示例在问题中表示的内容创建包装函数,例如,

PrefSingleton.getInstance().writePreference("exampleSetting", "off");

PrefSingleton.getInstance().writePreference("exampleSetting", "off");

and the implementation could be something like this:

实现可能是这样的:

// Within Singleton class

public void writePreference(String key, String value){
     Editor e = mMyPreference.edit();
     e.putString(key, value);
     e.commit();
}

From your first activity, activate the singleton class, in this manner, something like this:

从您的第一个活动开始,以这种方式激活单例类,如下所示:

PrefSingleton.getInstance().Initialize(getApplicationContext());

The reason I risk down-vote, is, using global static classes can be a bad idea and goes against the practice of programming fundamentals. BUThaving said that, as nit-picky aside, it will ensure only the one and only object of the class PrefSingletoncan exist and be accessible regardless of what activities the code is at.

我冒险投反对票的原因是,使用全局静态类可能是一个坏主意,并且违背了编程基础的实践。但话虽如此,除了挑剔之外,它将确保该类中只有一个且唯一的对象PrefSingleton可以存在并且可以访问,而不管代码处于什么活动。

回答by gobernador

I would extend Applicationand include the SharedPreferences.Editoras a field with a getter.

我会扩展Application并包含SharedPreferences.Editor一个带有吸气剂的字段。

public class APP extends Application {
    private final SharedPreferences settings = getSharedPreferences("prefs", 0);
    private final SharedPreferences.Editor editor = settings.edit();

    public SharedPreferences.Editor editSharePrefs() {
        return editor;
    }
}

Then you can access it from any Activitywith

然后你可以从任何访问它Activity

((APP) getApplication()).editSharePrefs().putString("examplesetting", "off");
((APP) getApplication()).editsharePrefs().commit();

Alternatively, you could also throw in the method

或者,你也可以抛出方法

    public static APP getAPP(Context context) {
        return (APP) context.getApplicationContext();
    }

Although, this would simply change the calls you make to

虽然,这只会改变您拨打的电话

APP.getAPP(this).editSharePrefs().putString("examplesetting", "off");
APP.getAPP(this).editsharePrefs().commit();

So it really is a personal preference, which looks cleaner to you.

所以这真的是个人喜好,对你来说看起来更干净。

回答by loikkk

I would do this following :

我会这样做:

public class BaseActivity extends Activity {

        protected boolean setInHistory;
        protected SharedPreferences sharedPrefs;

            @Override
        protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    setInHistory = true;
       }


}


public class MainActivity extends BaseActivity {

         public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

              System.out.println(setInHistory+" <-- setInhistory");

          }
}

Then can access sharedPrefs because it is protected then it's accessible through the package.

然后可以访问 sharedPrefs 因为它受到保护然后可以通过包访问。

In the console you have : true <-- setInhistory

回答by Clover

Use a Helper class to get all you want,make the methods static.This is how ADW do.

使用 Helper 类来获得你想要的一切,使方法静态。这就是 ADW 所做的。