getSharedPreferences() 中的 String 参数有什么作用?

What does the String parameter in getSharedPreferences() do?

编辑: 提供的 "duplicate" 没有解决我的问题,因为它没有完全回答我的问题。 (缺少有关第二个参数的信息)。


这个问题是为了给Android开发新手清除信息,不是解决我自己的问题。请重新考虑否决票。

所以,方法如下:

getSharedPreferences(string, Context.MODE_PRIVATE);

我不太明白第一个参数的作用。它有什么作用?如果我们将某些内容保存到 SharedPreferences 我们使用密钥,为什么会有第一个参数?

getSharedPreferences()中的String参数是存储您提供的键和值的文件名。例如:

SharedPreferences.Editor s = getSharedPreferences("Pref",Context.MODE_PRIVATE).edit();
s.putInt("someKey",0);
s.apply();

将在您的应用中创建一个名为 Pref 的输出文件,其中包含您要输入的密钥。

Android Developer Documentation for getSharedPreferences() 中所述,该方法的完整签名是:

SharedPreferences getSharedPreferences (String name, int mode)

正式签名提供了第一个参数的名称,name,这是对答案有用的信息。 name 参数是位于应用程序私有存储中的 XML 首选项文件的基本名称(无文件扩展名)。

例如,此调用将 return SharedPreferences 实例允许读取和写入应用程序的 settings.xml 首选项文件:

SharedPreferences sharedPrefs = getSharedPreferences("settings", Context.MODE_PRIVATE);

如官方文档所述,returned SharedPreferences 对象是一个单实例对象,所有调用者共享同一文件名。这意味着给定的调用并不一定意味着文件 IO 以读取给定的首选项,但 可能 导致同一应用程序中线程之间的线程同步。

如果指定的文件在调用 getSharedPreferences() 之前不存在,则将创建该文件。第二个参数,mode,是创建文件时使用的模式,应该设置为Context.MODE_PRIVATE(或者它的整数值0);其他模式值未记录为允许的,不应使用。与创建任何文件时一样,指示模式 Context.MODE_PRIVATE 将在应用程序的私有存储中定位文件,正如预期用于 getSharedPreferences().

SharedPreferences 实例中将值 (999) 写入键 (setting) 的示例如下:

Context context = getActivity();
SharedPreferences sharedPrefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("setting", 999);
editor.apply();

从同一个键读取值是这样完成的:

Context context = getActivity();
SharedPreferences sharedPrefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
sharedPrefs.getInt("setting", 0);

可以在 Saving Key-Value Sets page in the Android Getting Started Guide.

中找到其他使用信息

请注意,getSharedPreferences()getPreferences() 的通用版本,对于常见的应用程序首选项,它通常是更好的选择。除了能够通过 getSharedPreferences() 指定要使用哪个首选项文件之外,这两种方法在功能和行为方面都是相同的。根据 getPreferences() 文档,它只是用“this activity's class name as the preferences name”调用 getSharedPreferences()getSharedPreferences()).

的第一个参数