我们如何在服务和活动之间传递复杂的数据(例如,employee对象)?
在这里,服务和活动在不同的包中。可能是不同的应用。
最佳答案
首先序列化要传递的对象。
将序列化对象放入intent extras中。
在接收端,只需获取序列化对象,反序列化它。
说,
Employee employee = new Employee();
然后,
intent.putExtra("employee", serializeObject(employee));
接收时,
byte[] sEmployee = extras.getByteArray("employee");
employee=(employee)反序列化对象(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();
}
}
}