如何从 IntentService 返回对象?
我的 Activity 启动一个 IntentService,然后调用远程 API。然后,我需要将结果数据传递回活动(通过 BroadcastReceiver)。在应用程序的其余部分中,此数据封装在单个类中,并使用原始成员变量保存数据。但当结果通过 Intent 传递时,我的选择受到限制,因为我无法跨越边界传递标准 Java 对象。我正在寻找一种简洁的方法来通过 Intent 传递这样的对象,而不需要编写大量的重复代码。
选项:
- 在我的班级上实施 Parcelable。实现/维护很繁琐,
- 单独传递每个成员变量,并在另一侧重建对象。实施/维护繁琐
- 使用 AIDL 来指定合约。以前从未这样做过,不知道这样做是否合适。
- 序列化该对象并将字符串传递给活动。传递 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:
- Implement Parcelable on my class. Tedious to implement/maintain
- Pass each member variable individually, and reconstruct the object on the other side. Tedious to implement/maintain
- Use AIDL to specify the contract. Never done it before, not sure how appropriate this is.
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此远程 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.