0

Let's suppose I want to write an instant messenger client.
I guess there will be at least 2 activities:

UserManagerActivity - enables to manage accounts and logging in.
MainActivity - displaying contacts list etc.

But if I do it this way, there'll be some objects that should be accessible for both of them:

ConnectionManager - will be used for logging in, sending/receiving messages etc.
UserManager - holding information about users.
MusicPlayer - playing sounds.


So, what is the most elegant way to give both activities access to these objects?

I've heard about 4 possibilities:
- Using singleton pattern.
- Passing objects between activities using Bundle.
- Extending Application class.
- Using Service class (seems complicated to me).

  1. Which option do you think is the best one?

  2. Aren't globally accessible classes a sign of a bad project?

  3. How can I learn to design elegant and efficient applications "skeletons"?

Thanks in advance!

user2203031
  • 402
  • 3
  • 14
  • Q: Aren't globally accessible classes a .. bad sign?" A: No. They are often the *ideal* solution. I would consider using an Application class: [Android Global Variable](http://stackoverflow.com/questions/1944656/android-global-variable). Q: How can I learn to design elegant and efficient applications "skeletons"? A: Study others' code. And learn from your own successes and not-so-successes ;) IMHO... – paulsm4 Mar 23 '13 at 20:19
  • 1
    Old joke: A guy gets into a cab in New York City and asks the cab driver, "How do I get to Carnegie Hall?" The cabbie replies: "Practice, practice, practice". Also applicable to programming, IMHO... – paulsm4 Mar 23 '13 at 20:22

1 Answers1

3

Android created the Application class, if only in part, to handle this very case. They guarantee that there will only ever be 1 instance of it.

http://developer.android.com/guide/faq/framework.html

Bill Mote
  • 12,644
  • 7
  • 58
  • 82
  • 1
    Additionally, the easiest way is to keep a reference of an activity or both in the Application class, make public whatever members you are interested in and that's it :) – crios Mar 23 '13 at 20:04