轻量级的储存:SharedPreferences的一个例子

SharedPreferences:轻量级的储存,故名思意是做存储用的,当我们需要保存用户的某些settings值,需要轻量级的记忆操作等时使用!

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:表示当前文件可以被其他应用写入.
例如:

write(index,context);//传一个index值过来!

private void write(int key,Context context){
SharedPreferences preferences = context.getSharedPreferences("index", Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putInt("indexKey", key);
Log.i("TAG", "MyReceiver's key="+key);
editor.commit();
}


系统会生成一个index.xml文件储存在内存里!

private static boolean getDataFromSharePre(){//此时可以拿到存储的值进行判断了
SharedPreferences preferences = context.getSharedPreferences("index", Context.MODE_PRIVATE);
return (preferences.getInt("indexKey", 0)==5)?true:false;
}

当机器关机后,该文件依然存在,重启时可拿到这个文件进行对应判断操作了!

附:if ("android.intent.action.BOOT_COMPLETED".equals(action)) {//开机广播

你可能感兴趣的:(轻量级的储存:SharedPreferences的一个例子)