官方文档介绍:
Using Shared Preferences
The SharedPreferences
class provides a general framework that allows you to save
and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences
to
save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, seePreferenceActivity
,
which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences
object for your application, use one of two methods:
-
getSharedPreferences()
- Use this if you need
multiple preferences files identified by name, which you specify with the first parameter. -
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.
To write values:
-
Call
edit()
to get aSharedPreferences.Editor
. -
Add values with methods such as
putBoolean()
andputString()
. -
Commit the new values with
commit()
To read values, use SharedPreferences
methods such as getBoolean()
and getString()
.
a.示例程序:保存用户设置的数据
/** * 保存各项参数 * @param name 姓名 * @param age 年龄 */ public void save(String name, int age) { SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE); Editor edit = preferences.edit(); edit.putString("name", name); edit.putInt("age", age); edit.commit(); }
在保存之后,sharedPreferences将会把数据保存在 /data/data/<应用程序包名>/shared_pres/目录下,且使用xml方式保存数据
示例程序保存的数据是:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <int name="age" value="23" /> <string name="name">g形成</string> </map>
b.示例程序:从sharedPreferences中读取数据
/** * @return 返回参数设置数据 */ public Map<String, String > getPreferences(){ Map<String, String> params = new HashMap<String, String>(); SharedPreferences sp = context.getSharedPreferences("preferences", Context.MODE_PRIVATE); params.put("name", sp.getString("name", "")); params.put("age", String.valueOf(sp.getInt("age", 0))); return params; }