Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you serialize Android Intents?

Android Intents have a convenient toURI() method which the API docs seem to indicate is a way to serialize an Intent to a URI, and then later parse it back into an Intent. Unfortunately, in testing this functionality I found that it does not serialize all extras, just the primitive types (boolean, int, long, float, String). If an intent specifies any Parcelable or array extras then those will get lost.

Where (if anywhere) is this limitation documented? Is there some obvious reason for this behavior (I can imagine some difficulties with Parcelables)? And most importantly, is there a recommended way to serialize and parse Intents?

My current implementation simply writes Intent components (action, categories, data uri, and extras) to a SharedPreferences. This strategy does not support Parcelables.

like image 626
Alan Avatar asked May 31 '11 14:05

Alan


1 Answers

Android Intents have a convenient toURI() method which the API docs seem to indicate is a way to serialize an Intent to a URI, and then later parse it back into an Intent.

Not really.

Where (if anywhere) is this limitation documented?

I would not have expected extras to be included in the Uri at all. The point behind this sort of Uri generation would be to show you how to add the Uri as a link on a Web site, and you should not need extras for that scenario.

toURI() is not serialization.

And most importantly, is there a recommended way to serialize and parse Intents?

No. In particular, Parcelable cannot be serialized, by definition.

My current implementation simply writes Intent components (action, categories, data uri, and extras) to a SharedPreferences.

That approach is simply bizarre.

Use a database. If you were attacked by a database as a young child and therefore live in abject fear of databases, serialize using JSON, XML, or Serializable/ObjectOutputStream to a file. Use SharedPreferences for user preferences.

This strategy does not support Parcelables.

Nor should it. Nor can it. Parcelable is designed to convert an object graph into a memory block for use in a running device only. It is not a long-term persistence mechanism.

like image 68
CommonsWare Avatar answered Nov 11 '22 21:11

CommonsWare