概念
SharedPreferences:是android提供的一个轻量级的储存方式,当我们需要保存用户的某些settings值,需要轻量级的记忆操作等时使用!
SharedPreferences的四种操作模式: Context.MODE_PRIVATE Context.MODE_APPEND Context.MODE_WORLD_READABLE Context.MODE_WORLD_WRITEABLEContext.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件. Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件. MODE_WORLD_READABLE:表示当前文件可以被其他应用读取. MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.例子
存
/* * 存 */write("of",time(),ftv4,getActivity());write("ff",time(),ftv4,getActivity());write("af",time(),ftv4,getActivity());write("eo",time(),ftv4,getActivity());...private void write(String s,String time,int odo, Context context){ SharedPreferences preferences = context.getSharedPreferences(s, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("time", time); editor.putInt("odo", odo); editor.commit(); } .../* * 拿到当前的时间 */ public String time() { Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time=format.format(date); return time; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
取
private void getDataFromSharePre(){ //此时可以拿到存储的值进行判断了 SharedPreferences preferences_eo = getActivity().getSharedPreferences("eo", Context.MODE_PRIVATE); SharedPreferences preferences_of = getActivity().getSharedPreferences("of", Context.MODE_PRIVATE); SharedPreferences preferences_ff = getActivity().getSharedPreferences("ff", Context.MODE_PRIVATE); SharedPreferences preferences_af = getActivity().getSharedPreferences("af", Context.MODE_PRIVATE); time_eo = preferences_eo.getString("time", ""); time_of = preferences_of.getString("time", ""); time_ff = preferences_ff.getString("time", ""); time_af = preferences_af.getString("time", ""); odo_eo = preferences_eo.getInt("odo", 0); odo_of = preferences_of.getInt("odo", 0); odo_ff = preferences_ff.getInt("odo", 0); odo_af = preferences_af.getInt("odo", 0); tx_time_eo.setText(""+time_eo); tx_time_of.setText(""+time_of); tx_time_ff.setText(""+time_ff); tx_time_af.setText(""+time_af); tx_odo_eo.setText(""+odo_eo+"m"); tx_odo_of.setText(""+odo_of+"m"); tx_odo_ff.setText(""+odo_ff+"m"); tx_odo_af.setText(""+odo_af+"m"); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26