简体   繁体   English

如何在Android中使用Intents发送自定义数据对象?

[英]How to send custom data objects with Intents in Android?

Intents in Android are an elegant way to pass messages between uncoupled components, but what if you want to send extra data with the Intent? Android中的意图是在非耦合组件之间传递消息的一种优雅方式,但是如果要使用Intent发送额外数据该怎么办? I know you can add various value types, and objects that implement Parcelable, as extras, but this doesn't really cater for sending user defined types locally (ie not over a remote interface). 我知道你可以添加各种值类型,以及实现Parcelable的对象作为附加功能,但这并不真正适合在本地发送用户定义的类型(即不通过远程接口)。 Any ideas? 有任何想法吗?

In your type, you can implement the Serializable interface and call the Intent.putExtra(String, Serializable) method to include it in the intent. 在您的类型中,您可以实现Serializable接口并调用Intent.putExtra(String, Serializable)方法将其包含在intent中。 I considered doing it myself for a similar problem, but opted to just put the data in a bundle because my type would only have had two fields and it just wasn't worth the effort. 我考虑过自己做类似的问题,但是选择将数据放在一个包中,因为我的类型只有两个字段而且不值得努力。

This is how it could work, assuming that you have implemented Serializable on Foo: 假设您已经在Foo上实现了Serializable ,这就是它的工作原理:

Foo test = new Foo();
test.Name = "name";
test.Value = "value";

Intent intent = new Intent();
intent.putExtra("test", test);

If you want to pass objects within a single process you can implement your own Application to maintain global state: 如果要在单个进程中传递对象,可以实现自己的Application以维护全局状态:

Base class for those who need to maintain global application state. 需要维护全局应用程序状态的基类。 You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created. 您可以通过在AndroidManifest.xml的标记中指定其名称来提供自己的实现,这将导致在创建应用程序/包的进程时为您实例化该类。

When you say locally, does that mean sending the user defined types across the Activities/ local Services that belongs to same APK? 当你在本地说,这是否意味着在属于同一个APK的Activities / local Services中发送用户定义的类型? As long as user-defined type is parcelable it can be sent as extras in intent and can be processed in onStartCommand() of service/activity. 只要用户定义的类型是parcelable,它就可以作为intent的附加内容发送,并且可以在service / activity的onStartCommand()中处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM