可以用SharedPreferences API存储键值对,并且提供了简单的访问方法,还可以控制SharedPreferences文件的访问权限。
下面介绍SharedPreferences API的使用方法。
得到一个SharedPreferences对象
用以下方法得到或创建一个SharedPreferences文件对象
getSharedPreferences()
— Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from anyContext
in your app.getPreferences()
— Use this from anActivity
if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.
例如,下面代码在一个Fragment中执行,得到一个由R.string.preference_file_key资源标志的SharedPreferences文件,并用private模式打开,表示只能在你自己的app中访问这个文件
Context context = getActivity();
S