tags:

views:

48

answers:

3

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? 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?

A: 

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.

Suresh
Locally as in not via aidl, and all in the same process, the same application. The thing is, implementing parcelable for complex custom data types can actually be quite painful, when all I need to do is transfer an object with an Intent ...
MalcomTucker
A: 

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.

Josef
ok, so use Application as a kind of broker / storage for shared data?
MalcomTucker
exactly, you can implement it as a repository if you need it
Josef
+1  A: 

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);
Dan