如何在Service和Activity之间传递复杂数据?

时间:2012-03-20 05:13:10

标签: android service android-activity

我们如何在服务和活动之间传递复杂数据(例如,员工对象)?

此处,服务和活动位于不同的包中。可能是不同的应用。

2 个答案:

答案 0 :(得分:3)

  • 首先序列化您要传递的对象。
  • 将序列化对象放在intent extras中。
  • 在接收端,只需获取序列化对象,然后对其进行反序列化。

说,

 Employee employee = new Employee();

然后,

intent.putExtra("employee", serializeObject(employee));

收到时,

byte[] sEmployee = extras.getByteArray("employee");

employee =(Employee)deserializeObject(sEmployee);

FYI,

public static byte[] serializeObject(Object o) throws Exception,IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    try {
        out.writeObject(o);
        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();

        return buf;
    } catch (IOException e) {
        Log.e(LOG_TAG, "serializeObject", e);
        throw new Exception(e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

public static Object deserializeObject(byte[] b)
        throws StreamCorruptedException, IOException,
        ClassNotFoundException, Exception {
    ObjectInputStream in = new ObjectInputStream(
            new ByteArrayInputStream(b));
    try {
        Object object = in.readObject();
        return object;
    } catch (Exception e) {
        Log.e(LOG_TAG, "deserializeObject", e);
        throw new Exception(e);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

答案 1 :(得分:1)

您需要通过实施 Parcelable 可序列化界面来创建复杂数据类型对象(例如Employee)。

然后通过将 parcelable 可序列化对象传递到其中来创建Intent并使用 putExtra()

然后在目标类中使用 getParcelableExtra() getSerializableExtra()等来获取该对象。