自己学习使用,轻喷
SharedPreferences保存用户偏好设置
SharedPreferences类是一个轻量级的存储类,特别适合用于保存软件配置参数
使用SharedPreference保存数据,其背后是用xml文件存放数据,文件存放于/data/dada/<package name>/shared_prefs
========
PreferenceService service = new PreferenceService(getApplicationContext());
service.save(name, age);
Toast.makeText(getApplicationContext(), "save success", Toast.LENGTH_LONG).show();
HashMap<String, String> map = (HashMap<String, String>) service.getPreferences();
Log.i(TAG, map.get("name"));
Log.i(TAG, map.get("age"));
Service 服务类
========SharedPreferenceService=====
如果需要背后的sharedPreference可以被其他应用读写:可以添加如下mode:
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE
public class PreferenceService { private Context context; public PreferenceService(Context context){ this.context = context; } /** * 保存到sharedpreference里 * @param name * @param age * @throws Exception */ public final void save(String name, String age) throws Exception{ //getSharedPreferences第一个参数是文件名,但不需要加后缀.xml,系统默认就是xml格式 SharedPreferences preferences = context.getSharedPreferences("myPreference", Context.MODE_PRIVATE); Editor editor = preferences.edit(); //一定要获得编辑器 editor.putString("name", name); editor.putString("age", age); editor.commit(); //提交修改 } /** * 从以保存的xml文件中读取 * @return */ public Map<String, String> getPreferences(){ Map<String, String> params = new HashMap<String, String>(); SharedPreferences preference = context.getSharedPreferences("myPreference", Context.MODE_PRIVATE); params.put("name", preference.getString("name", "default")); params.put("age", preference.getString("age", "default")); return params; } }