SharedId实现应用之间的数据共享+SharedPreferences保存用户定义类型对象
通常提到android应用之间的数据共享,最先想到的总是ContentProvider,其实还有一种方法也可以实现应用之间的数据共享--配置SharedId

?
流程:
(1) 修改数据提供方和数据使用方的AndroidManifest.xml 中的<manifest>节点的属性
android:sharedUserId="com.mysharedId" 这里属性的值,数据提供方和调用方必须一致并且不能只有一个单词也就是说最少有一个“.”。
(2)使用
在数据使用Activity对象的createPackageContext()方法得到数据提供方的Context
有了这个Context你就可以得到数据提供方的资源了,通过getResources(),getString(),getAsset()等方式
?Context friendContext = this.createPackageContext("com.my.server", Context.CONTEXT_IGNORE_SECURITY);
在demo中还用到了?SharedPreferences保存自定义的实例对象,得导入一个类库commons-codec-1.4.jar
我在demo 中为了方便用的是String类型不是自定义的类型,但是你在这里可以将String类型替换成任意类型
实例代码如下:
//保存对象
?public void saveSetting(String str)
?{
??//将对象转换成对象流,然后通过SharedPreferences保存,在得到对象时是一个逆向的过程先得到对象流然后得到对象
??ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
??ObjectOutputStream oStream;
??try {
???oStream = new ObjectOutputStream(baoStream);
???oStream.writeObject(str);
??} catch (IOException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
??SharedPreferences sharedPreferences = getSharedPreferences(
????"emotions.xml", Activity.MODE_PRIVATE);
??String productBase64 = new String(
????org.apache.commons.codec.binary.Base64.encodeBase64(baoStream
??????.toByteArray()));
??SharedPreferences.Editor editor = sharedPreferences.edit();
??editor.putString("info", productBase64);
??editor.commit();
?}
//得到对象
?
public String? getCharSequence(Context context)
?{
??SharedPreferences sharedPreferences = context.getSharedPreferences(
????"emotions.xml", Activity.MODE_PRIVATE);
??String str = null;
??String proString = sharedPreferences.getString("info", "");
??if (proString != null && !"".equals(proString)) {
???byte[] base64Bytes = org.apache.commons.codec.binary.Base64
?????.decodeBase64(proString.getBytes());
???ByteArrayInputStream bari = new ByteArrayInputStream(base64Bytes);
???ObjectInputStream oInputStream;
???try {
????oInputStream = new ObjectInputStream(bari);
????str = (String)oInputStream.readObject();
???} catch (StreamCorruptedException e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???} catch (IOException e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???} catch (ClassNotFoundException e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???}
??}
??return str;
?}
具体内容请看demo
?