獲取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;
}
}