【问题标题】:Shared preferences with different context具有不同上下文的共享偏好
【发布时间】:2016-05-29 09:25:12
【问题描述】:

这两者有什么区别:

SharedPreferences prefs = getDefaultSharedPreferences(Application context);

SharedPreferences prefs = getDefaultSharedPreferences(Activity context);

我不知道该使用哪一个?我想将 prefs 设为静态,以便我可以在我的应用程序的任何地方使用它。可以吗?

【问题讨论】:

    标签: android sharedpreferences android-preferences android-context android-sharedpreferences


    【解决方案1】:

    在这种情况下,这无关紧要。

    如果您查看the source code,您会看到您传入的上下文用于为您的偏好创建一个名称。这是通过调用context.getPackageName() 来完成的。因此,只要两个上下文返回相同的包名称(并且对于您的应用程序中的任何上下文都应该相同),使用这两者就没有区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2014-12-31
      相关资源
      最近更新 更多