Greggy
Greggy

Reputation: 1029

Using Singletons Between Android Application Activities?

I have a multiple Activity application that progresses the user from entering an IP/Host address, to entering some data (another Activity), to viewing a stream of video frames (yet another Activity). I share the Socket between the Activities by creating a singleton. Is this considered a bad pattern to use for an object that cannot be serialized?

I have looked all morning through some of these posts and others through out the web and the best that I can come up with is there is no real easy way, but this one seems very easy to me. The only other approach I think has merit is a custom Application object.

Any insight by people who have worked with singletons across Activities I would really like to hear of any problems I may not be aware of that might get me later... Thanks!!

Upvotes: 2

Views: 1270

Answers (1)

Eric Levine
Eric Levine

Reputation: 13564

The downside to your approach is that you cannot rely on the singleton's data structures to always be kept around in memory. Your best bet is to persist information in either SharedPreferences or a SQLite database.

It sounds like your singleton might be a good candidate for a Service. Services are meant for long runnning operations that do not have any UI. Multiple Activities can bind to a service and interact with it. Unlike a singleton, if/when your service gets killed, you will get lifecycle hooks to deal with it appropriately. You can also set it to be restarted when appropriate.

Upvotes: 3

Related Questions