getDefaultSharedPreferences()和getPreferences()有什么区别? [英] What's the difference between getDefaultSharedPreferences() and getPreferences()?
问题描述
我目前正在参加开发Android应用" Udacity课程.在第3课:新活动和意图>使用SharedPreferences"部分中,讲师要求我在Android Developer网站上进行深入了解,以了解如何从SharedPreferences
获取用户首选项.但是,我发现官方文档和本课程的解决方案有所不同.
I'm currently taking the "Developing Android Apps" Udacity course. In the "Lesson 3: New Activities and Intents > Use SharedPreferences" segment, the instructor asked me to dig around the Android Developer site for how to get the user preferences from SharedPreferences
. However, I found it different between the official documentation and the course's solution.
Udacity课程的解决方案说,为PreferenceActivity
,您应该致电:
The Udacity course's solution says, to grab a SharedPreferences
instance for the PreferenceActivity
, you should call:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
(其中getActivity()
在这里只是Context
,因为它在Fragment
内部被调用.)
(where getActivity()
is simply the Context
here because it's called inside a Fragment
.)
在Android开发者网站上官方文档表示您应该致电:
While the official documentation on Android Developer Site indicates that you should call:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE)
那么PreferenceManager.getDefaultSharedPreferences(Context context)
和Activity.getPreferences(int mode)
有什么区别?
请注意::该问题不涉及有关getSharedPreferences()
的任何内容,该文件需要文件名.这与getPreferences()
和getDefaultSharedPreferences()
之间的区别有关.
Please note: This question does not involve anything about getSharedPreferences()
which requires a file name. It's about the difference between getPreferences()
and getDefaultSharedPreferences()
.
谢谢.
推荐答案
根据您提供给Android文档的链接
Acoording to the link you provided to Android documentation
getSharedPreferences()-如果您需要多个用名称标识的首选项文件,请使用第一个参数指定该文件.
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences()-如果您的活动仅需要一个首选项文件,请使用此选项.因为这将是活动"的唯一首选项文件,所以您无需提供名称.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
就是这样,当要保存/检索的数据可以从应用程序中的不同活动中使用时,请使用getSharedPreferences.如果这些首选项仅在一个Activity中使用,则可以使用getPreferences.
So it is, use getSharedPreferences when the data you want to save/retrieve can be used from different activities in the app. If those preferences will only be used in one Activity, you can use getPreferences.
还请注意,正如帖子中所说,链接的"getDefaultSharedPreferences将使用默认名称,例如" com.example.something_preferences",但getSharedPreferences将需要一个名称"
also note that as said in the post you linked 'getDefaultSharedPreferences will use a default name like "com.example.something_preferences", but getSharedPreferences will require a name'
这篇关于getDefaultSharedPreferences()和getPreferences()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!