我们如何在服务和活动之间传递复杂数据(例如,员工对象)?
此处,服务和活动位于不同的包中。可能是不同的应用。
答案 0 :(得分:3)
说,
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()等来获取该对象。