获取SharedPreferences的两种方式:
1 调用Context对象的getSharedPreferences()方法
2 调用Activity对象的getPreferences()方法
两种方式的区别:
调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一应用程序下的其他组件共享.
调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在该Activity中使用.
SharedPreferences的四种操作模式:
Context.MODE_PRIVATE
Context.MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.
public class UtilsSharedPreferences {
public static boolean saveUserInfo(Context context, String number, String password) {
try {
SharedPreferences sp = context.getSharedPreferences("user", Context.MODE_PRIVATE);
//获得一个编辑对象
Editor edit = sp.edit();
//存数据
edit.putString("number", number);
edit.putString("password", password);
//提交数据
edit.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static Map<String, String> getUserInfo(Context context) {
SharedPreferences sp = context.getSharedPreferences("user", Context.MODE_PRIVATE);
String number = sp.getString("number", null);
String password = sp.getString("password", null);
if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(password)) {
Map<String, String> userInfoMap = new HashMap<String, String>();
userInfoMap.put("number", number);
userInfoMap.put("password", password);
return userInfoMap;
}
return null;
}
}