gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:13:50 29 4
gpt4 key购买 nike

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

在这里,Service 和 Activity 在不同的包中。可能是不同的应用程序。

最佳答案

  • 首先序列化你要传递的对象。
  • 将序列化对象放入 intent extras 中。
  • 在接收端,获取序列化后的对象,反序列化即可。

说,

 Employee employee = new Employee();

然后,

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

接收时,

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

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();
}
}
}

关于android - 如何在Service和Activity之间传递复杂的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781660/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com