一、SharedPreferences介绍
Interface for accessing and modifying preference data returned by
Context.getSharedPreferences(String, int)
. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor
object to ensure the preference values remain in a consistent state and control when they are committed to storage. (摘自Android API)
SharedPreferences是轻量级存储类,存储信息以XML文件的形式保存在/data/data/PACKAGE_NAME /shared_prefs 目录下
二、SharedPreferences用法
1、存储数据
SharedPreferences pref = Context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
//PREFERENCES_NAME 存储名称Context.MODE_APPEND 存储模式
/*
存储模式有4种,分别为:
①MODE_PRIVATE:the default mode, where the created file can only be accessed by the calling application
(or all applications sharing the same user ID).
②MODE_APPEND:if the file already exists then write data to the end of the existing file instead of erasing it
③MODE_WORLD_READABLE:allow all other applications to have read access to the created file.
④MODE_WORLD_WRITEABLE:allow all other applications to have write access to the created file.
后两种存在安全漏洞,不推荐使用
*/
Editor editor = pref.edit();
editor.putString("key_string", value_string);
editor.commit();
2、取出数据
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
String value = pref.getString("key_string", "default_value");