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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值