我们如何在一个服务和活动之间传递复杂数据(比如员工对象)?
这里的服务和活动位于不同的包中,可能是不同的应用程序。
这里的服务和活动位于不同的包中,可能是不同的应用程序。
例如,
Employee employee = new Employee();
intent.putExtra("employee", serializeObject(employee));
当接收数据时,
byte[] sEmployee = extras.getByteArray("employee");
员工 = (Employee) deserializeObject(sEmployee);
顺便提一下,
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或Serializable接口来创建复杂的数据类型对象(例如Employee)。
然后创建Intent并使用putExtra()将parcelable或serializable对象传递给它。
然后在目标类中使用getParcelableExtra()或getSerializableExtra()等方法获取该对象。