您的位置:首页 > 其它

关于ShareUserId需要注意的几个问题

2013-03-08 17:00 746 查看
首先粘一段官方文档对ShareUserId的说明:

android:sharedUserId
The name of a Linux user ID that will be shared with other applications. By default, Android assigns each application its own unique user ID. However, if this attribute is set to the same value for two or more applications, they will all share the same ID — provided that they are also signed by the same certificate. Application with the same user ID can access each other's data and, if desired, run in the same process.
网上对ShareUserId的说明已经很多,大部分都重复了,我在此只是补充说明一下:

如果两个应用的ShareUserId相同,则共享对方的data目录下的文件,包括SharePreference, file, lib等文件,而不是很多人所想的资源文件。

注意: 要共享资源文件(图片,layout, string等),并不需要ShareUserId相同,普通方法就能拿到,但前提是你自己的应用里已经有了名字相同的资源文件,这样R文件才能找到那个id,否则编译器报错。 方法如下:

try {
Context ct=this.createPackageContext ("com.example.shareb", Context.CONTEXT_IGNORE_SECURITY);
String str = ct.getString(R.string.share);
Log.d("Test", str);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

也就是说,当前项目里也必须有个string的名字叫share,这样编译器不会报错。当程序真正运行时,会自动寻找com.example.shareb 这个程序下的名字为share的string。

当然,如果ShareUserId相同,则可以通过如下方法访问对方SharePrefrence中的内容:

try {
Context ct=this.createPackageContext ("com.example.shareb", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sp = ct.getSharedPreferences("shareb", MODE_PRIVATE);
String str2 = sp.getString("haha", "");
Log.d("Test", "share preference-->" + str2);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
此时访问的是com.example.shareb这个应用下名字为shareb的xml文件中的key为haha的值(有点晕吧?)

于是有人可能会想: 会不会有安全问题啊? 比如我把我的ShareUserId搞得和你的一样,不就能任意访问你的文件了吗? 答案是否定的。 只有在如下条件下,才可以利用ShareUserId共享文件。

***两个应用ShareUserId相同,包名相同或不同,打包时签名文件必须相同***

否则,在如下情况下,第二个安装包在安装时会失败,错误为[INSTALL_FAILED_SHARED_USER_INCOMPATIBLE]:

1.包名相同,签名相同,ShareUserId不同

2.包名相同或不同,ShareUserId相同,签名不同

所以建议大家在以后开发全新应用的时候,最好将ShareUserId加上,方便以后扩展。 否则,以后想加都没法加了,因为线上版本没有ShareUserId,而升级版有,那么这两个包根本就不兼容,所以肯定更新失败!

什么? ShareUserId怎么加? 自己网上找吧!




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: