很多时候我们开发的软件需要向用户提供软件参数设置功能.
如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?
Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,
特别适合用于保存软件配置参数。
使用SharedPreferences保存数据,其背后是用xml文件存放数据
,文件存放在/data/data/<package name>/shared_prefs目录下:
SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "Sanjay");
editor.putInt("age", 3);
editor.commit();//提交修改
生成的itcast.xml文件内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">Sanjay</string>
<int name="age" value="3" />
</map>
因为SharedPreferences背后是使用xml文件保存数据,
getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,
名称不用带后缀,后缀会由Android自动加上。
方法的第二个参数指定文件的操作模式,共有四种操作模式,
如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,
可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
但需要注意的一点是,使用这个目前是不鼓励了。因为谷歌说道:
This constant was deprecated in API level 17.
Creating world-readable files is very dangerous, and likely to cause security holes in applications.
It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as
ContentProvider,BroadcastReceiver, andService. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore. File creation mode: allow all other applications to have read access to the created file.大意就是,这玩意会导致一些严重的问题。建议要共享数据就使用contentProvider,
BroadcastReceiver, 和Service. 来做。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,
这个方法默认使用当前类不带包名的类名作为文件的名称。
-----------------------------------------------------------------------
访问SharedPreferences中的数据代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回这个缺省值
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
如果访问其他应用中的Preference,
前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。
如:有个<package name>为cn.itcast.action的应用使用下面语句创建了preference。
getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,
然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("cn.itcast.action", Context.CONTEXT_IGNORE_SECURITY); SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("itcast", Context.MODE_WORLD_READABLE); String name = sharedPreferences.getString("name", ""); int age = sharedPreferences.getInt("age", 0);
如果不通过创建Context访问其他应用的preference,
可以以读取xml文件方式直接访问其他应用preference对应的xml文件,
如:
File xmlFile = new File(“/data/data/<package name>/shared_prefs/itcast.xml”);//<package name>应替换成应用的包名
本文介绍了在Android应用中如何使用SharedPreferences来保存和读取软件配置参数。详细解释了SharedPreferences的使用方法,包括数据的保存和读取流程,并展示了背后的XML文件存储形式。此外,还讨论了不同操作模式的区别及其安全性考量。
1万+

被折叠的 条评论
为什么被折叠?



