SharedPreferences 共享参数配置,在当前的上下文中如果要得到SharedPreferences 对象可以调用:
getSharedPreferences(String name, int mode)
getPreferences(int mode)
这两个方法有何区别呢?
看参数信息,第一个方法不难理解,分别是:文件名称、文件操作模式。
第二个方法参数只需要传入文件的操作模式,文件的名称默认为当前上下文对象的简单名称(当前方法调用所在类的名称)。
a. 保存共享参数配置信息,示例代码如下:
b. 获取共享参数配置信息,示例代码如下:
c. 访问其它应用程序中的共享参数配置信息,示例代码如下:
getSharedPreferences(String name, int mode)
getPreferences(int mode)
这两个方法有何区别呢?
看参数信息,第一个方法不难理解,分别是:文件名称、文件操作模式。
第二个方法参数只需要传入文件的操作模式,文件的名称默认为当前上下文对象的简单名称(当前方法调用所在类的名称)。
a. 保存共享参数配置信息,示例代码如下:
- SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
- // 获取表单中的属性值
- String name = edtName.getText().toString();
- String age = edtAge.getText().toString();
- // 得到共享配置对象保存配置信息
- Editor editor = pres.edit();
- editor.putString("name", name);
- editor.putString("age", age);
- // 调用commit方法保存配置信息
- editor.commit();
SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
// 获取表单中的属性值
String name = edtName.getText().toString();
String age = edtAge.getText().toString();
// 得到共享配置对象保存配置信息
Editor editor = pres.edit();
editor.putString("name", name);
editor.putString("age", age);
// 调用commit方法保存配置信息
editor.commit();
b. 获取共享参数配置信息,示例代码如下:
- SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
- edtName.setText(pres.getString("name", null));
- edtAge.setText(pres.getString("age", null));
SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
edtName.setText(pres.getString("name", null));
edtAge.setText(pres.getString("age", null));
c. 访问其它应用程序中的共享参数配置信息,示例代码如下:
- // 构建其它应用程序的上下文对象,用于取得应用的共享配置信息,第二个参数意思是忽略安全检查
- Context context = this.createPackageContext("com.jelly.pres", Context.CONTEXT_IGNORE_SECURITY);
- // 得到其它应用程序的共享参数配置对象
- SharedPreferences pres = context.getSharedPreferences("config", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
// 构建其它应用程序的上下文对象,用于取得应用的共享配置信息,第二个参数意思是忽略安全检查
Context context = this.createPackageContext("com.jelly.pres", Context.CONTEXT_IGNORE_SECURITY);
// 得到其它应用程序的共享参数配置对象
SharedPreferences pres = context.getSharedPreferences("config", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);