如何在服务和活动之间传递复杂的数据?
答
- 首先序列化您想要传递的对象。
- 将序列化对象置于意图附加。
- 在接收端,只需获取序列化对象,反序列化它。
说,
Employee employee = new Employee();
然后,
intent.putExtra("employee", serializeObject(employee));
而接收
,
byte[] sEmployee = extras.getByteArray("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();
}
}
}
答
您需要通过一个实现Parcelable或序列化界面来创建复杂数据类型的对象(例如员工)。
然后创建意图并使用putExtra()通过传递parcelable或序列化的对象到它。
然后在目标类中使用getParcelableExtra()或getSerializableExtra()等,以获得该对象。
看到这一个[通对象到活动](http://*.com/questions/8686938/how-to-pass-object-to-an-activity)。 – 2012-03-20 05:21:20
检查此示例:[Android - 使用意图将对象从一个活动发送到另一个活动](http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/) – 2012-03-20 06:28:42