如何从 IntentService 返回对象?

发布于 2024-12-01 03:18:09 字数 447 浏览 2 评论 0原文

我的 Activity 启动一个 IntentService,然后调用远程 API。然后,我需要将结果数据传递回活动(通过 BroadcastReceiver)。在应用程序的其余部分中,此数据封装在单个类中,并使用原始成员变量保存数据。但当结果通过 Intent 传递时,我的选择受到限制,因为我无法跨越边界传递标准 Java 对象。我正在寻找一种简洁的方法来通过 Intent 传递这样的对象,而不需要编写大量的重复代码。

选项:

  1. 在我的班级上实施 Parcelable。实现/维护很繁琐,
  2. 单独传递每个成员变量,并在另一侧重建对象。实施/维护繁琐
  3. 使用 AIDL 来指定合约。以前从未这样做过,不知道这样做是否合适。
  4. 序列化该对象并将字符串传递给活动。传递 Intent 是否有字符串长度限制?我认为可能存在性能问题。

我应该使用哪种方法,为什么?

My Activity starts an IntentService that then calls a remote API. I then need to pass the resulting data back to the Activity (through a BroadcastReceiver). Within much of the rest of the app this data is encapsulated in a single class, with primitive member variables holding the data. But as the results are passed across through an Intent I'm limited in my options as I can't pass a standard Java object across the boundary. I am looking for a neat and tidy way to pass objects like this through an Intent, without requiring large amounts of repetitive code needing to be written.

Options:

  1. Implement Parcelable on my class. Tedious to implement/maintain
  2. Pass each member variable individually, and reconstruct the object on the other side. Tedious to implement/maintain
  3. Use AIDL to specify the contract. Never done it before, not sure how appropriate this is.
  4. Serialise the object and pass the String through to the Activity. Is there a String length limit for passing through an Intent? I gather there can be performance issues.

Which approach should I use, and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七婞 2024-12-08 03:18:09

此远程 API 是否以某种方式(JSON 或 XML)序列化数据?您不能推迟反序列化直到它到达活动吗?

如果做不到这一点,我会认为序列化是最好的选择。 Parcelable 是一种特定类型的序列化,正如您所指出的,它的实现有点棘手,但如果您担心性能,它应该具有更高的性能。不过,除非您要处理大量流量,否则根据我的经验,序列化选项不应太慢。

Does this remote API serialize the data in some way (JSON or XML)? Can you not hold off on the deserializing until it reaches the Activity?

Failing this I would see serialization as the best option. Parcelable is a specific type of serialization which, as you point out is a little more tricky to implementent but should be more performant if you are concerned about performance. Unless you are handling a huge amount of traffic, though, the serialization option shouldn't be too sluggish in my experience.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文