kAmol
kAmol

Reputation: 1389

Singleton for multiple uses?

I am developing an android application in which I can/allowed to use only one instance of MediaPlayer(Singleton instance).

static MediaPlayer mp;
public static MediaPlayer getMediaPlayer() {
  if (mp == null) {
     mp = new MediaPlayer();
  }

  return mp;
}

Now This activity can be called for two purposes

  1. from within application (Say ABC)
  2. from any other application (say XYZ) for preview

This instance of mediaplayer is supposed to play either video or audio. So I have created a class which handles request(parameterized constructor to check for audio instance needed or video instance needed) and based on request, it creates required instance.

But the problem arises when Within application user is playing an audio file and user launched other application (XYZ) and requested to play video.

Now I am storing MediaPlayer's previous state (like which file it was playing and current position etc) and releasing MediaPlayer to be used for XYZ application for Video Playing. And once user stops playing video, ABC resumes playing audio file based on the stored instance.

So is this the right approach? Or I need to do modify the architecture of this task?

Please suggest w.r.t. design patterns

Upvotes: 2

Views: 94

Answers (2)

rusito23
rusito23

Reputation: 1003

Using singletons in Android for state persistance is something to be careful about.

Mabye you should investigate the activity lifecycle to understand in which cases you can loose the singleton instance (and therefore all the data stored inside it).

Here is some information

For instance when your app is running in the background, the cellphone can ask for memory and kill the instance of your singleton.

Upvotes: 1

Simeon Ikudabo
Simeon Ikudabo

Reputation: 2190

Here is an example Singleton that I would try:

public class MediaPlayer{


        private static MediaPlayer instance = new MediaPlayer();

        public static MediaPlayer getInstance() {
                return MediaPlayer.instance;
        }

}

Now you have a scenario in which you can create objects based on the getInstance() method which can only reference the same object which will ensure your singleton pattern. I tested it and attempted to make objects from this singleton pattern:

MediaPlayer t1 = MediaPlayer.getInstance();
MediaPlayer t2 = MediaPlayer.getInstance();
System.out.println(t1.equals(t2));

result:

true

Upvotes: 0

Related Questions