现在的位置: 首页 > 综合 > 正文

Android入门/利用SharedPreferences保存配置信息(十九)

2018年05月26日 ⁄ 综合 ⁄ 共 1552字 ⁄ 字号 评论关闭
SharedPreferences描述:
	利用SharedPreferences保存一些配置信息在本地 (XML)
	SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。
	使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下

#---------------------------------------割掉小JJ-------------------------------------------------------#
Context总共有四种模式,以下分别做解释:
	1.Context.MODE_PRIVATE = 0;		//私有的,只能被创建这个文件的当前应用访问,若创建的文件已经存在,则会覆盖掉原来的文件
	2.Context.MODE_APPEND = 32768;  //若文件不存在也会创建,若文件存在则在文件的末尾进行追加内容,也是私有的
	3.Context.MODE_WORLD_READABLE=1;//创建出来的文件可以被其他应用所读取
	4.Context.MODE_WORLD_WRITEABLE=2//允许其他应用对其进行写入。
#---------------------------------------割掉小JJ-------------------------------------------------------#
//CODE : 
public static final String PREFERENCE_KEY_USER_DEBUG_MODE = "debug_mode";
/**
	保存数据的过程
*/	
SharedPreferences sharedPreferences = context
		.getSharedPreferences("fileName", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putBoolean(PREFERENCE_KEY_USER_DEBUG_MODE, false);
editor.commit();
#---------------------------------------割掉小JJ-------------------------------------------------------#
/**
	读取保存数据的过程
*/
SharedPreferences sharedPreferences = context.getSharedPreferences("fileName", Context.MODE_PRIVATE);
/**
	sharedPreferences.getString(Key,default Value)
*/
boolean debugMode = sharedPreferences.getBoolean(PREFERENCE_KEY_USER_DEBUG_MODE,true);
#---------------------------------------割掉小JJ-------------------------------------------------------#
如果不通过创建Context访问其他应用的preference,可以以读取xml文件方式直接访问[其他应用]preference对应的xml文件,如:
File xmlFile = new File("/data/data/<package name>/shared_prefs/itcast.xml");//<package name>应替换成应用的包名

抱歉!评论已关闭.