为什么 SharedPreferences 使用上下文?

Why SharedPreferences use the context?

我尝试使用 SharedPreferences,但我不明白为什么我们需要上下文。

如果我用我的主 activity 上下文创建一个 SharedPreferences,我能得到另一个上下文的东西吗?

例如使用 intentService class

谢谢

IntentServiceContext 的子类(就像 ActivityApplication 和许多其他 Android 类 一样) .因此,您当然可以从 IntentService 创建 SharedPreferences。它将看到与应用程序中的任何 Activity 或其他 Context 相同的 SharedPreferences 值。 (这就是它被称为 shared 的原因。)您只需确保在一个上下文中在首选项的编辑器中对 apply()commit() 所做的更改,以便更改在其他地方可以看到。这些都包含在 the docs.

正在查看 Android Source Code。您会了解到 Context class 在内部维护一个共享首选项的静态 HashMap 以便快速访问:

private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs =
        new HashMap<String, SharedPreferencesImpl>();

所以你可以从任何 class 获得 SharedPreferences,比如 Intent ServiceActivity 等扩展 Context 并且它总是 return 同一个对象,如果同名。

注意:IntentService 如果您跟踪链,确实会扩展上下文:

IntentService extends Service
Service extends ContextWrapper
ContextWrapper extends Context

是的,这是没有意义的问题,但无论如何。 如您所知,SharedPreference.It 用于 存储私有原始数据。

在这里,关于私人数据条款。这意味着此数据存储到应用程序的存储路径中。即 data/data/yourpackageName/shared_prefs.

因此,要访问应用程序的存储,SharePreference 需要任何 运行 Activity.

的活动上下文

SharedPreferences 被读取并保存到磁盘。

因此 class 需要知道应用程序的位置 - 唯一知道的方法是通过上下文。

在标准 Java 中有全局(静态)对象,因此您可以像 System.getProperty("user.home") 那样访问用户的主目录。该系统未在 Android 中维护 - 在 Android 中,您需要使用上下文来访问应用程序的主目录