开发者

How to send custom data objects with Intents in Android?

开发者 https://www.devze.com 2023-01-10 02:19 出处:网络
Intents in Android are an elegant way to pass messages between uncoupled components, but what if you want to send extra data with the Inten开发者_运维技巧t? I know you can add various value types, and

Intents in Android are an elegant way to pass messages between uncoupled components, but what if you want to send extra data with the Inten开发者_运维技巧t? 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 (i.e. not over a remote interface). 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. 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 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:

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.


When you say locally, does that mean sending the user defined types across the Activities/ local Services that belongs to same APK? 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消