title: How to use single instance of MediaPlayer across all activities and fragments?
body: <p>I have several activities and fragments that displays songs from SD card and when I click on any of them, it plays. The problem is I have to create a new instance of media player in each of these activities and fragments. So, if I play a song in one activity and play another in another activity, both the songs are played simultaneously. I read about singleton class and making media player static but I need more information. Below is my code.</p>
  
  <pre><code>public class ArtistSongAlbumSong extends AppCompatActivity {
  
  ArrayList&lt;SongInfoModel&gt; ArtistSongAlbumSongList = new ArrayList&lt;&gt;();
  
  RecyclerView recyclerView_artistalbumsongs;
  
  ArtistSongAlbumSongAdapter artistSongAlbumSongAdapter;
  
  private static MediaPlayer player = new  MediaPlayer();
  
  Context isContext;
  
  private int currentIndex;
  
  
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_artistsongallsong);
  
      recyclerView_artistalbumsongs = findViewById(R.id.recyclerView_artistSongAllSong);
  
      isContext = ArtistSongAlbumSong.this;
  
      Long albumid = getIntent().getExtras().getLong("album_id");
  
      LinearLayoutManager aslinearLayoutManager = new LinearLayoutManager(getApplicationContext());
      recyclerView_artistalbumsongs.setLayoutManager(aslinearLayoutManager);
  
  
      Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
  
      String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
      Cursor cursor = getApplicationContext().getContentResolver().query(uri, null, selection, null, null);
      if (cursor != null) {
          if (cursor.moveToFirst()) {
              do {
                  String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                  String nameArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                  String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                  Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                  Long newAlbumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                  Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
                  Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumid);
  
                  if (newAlbumId.equals(albumid)) {
  
                      SongInfoModel s6 = new SongInfoModel(name, nameArtist, duration, data, albumArtUri);
                      ArtistSongAlbumSongList.add(s6);
                  }
  
              } while (cursor.moveToNext());
          }
  
  
          cursor.close();
  
          Collections.sort(ArtistSongAlbumSongList, new Comparator&lt;SongInfoModel&gt;() {
              @Override
              public int compare(SongInfoModel lhs, SongInfoModel rhs) {
                  return lhs.getSongName().compareTo(rhs.getSongName());
              }
          });
  
  
      }
  
  
  
  
  
      artistSongAlbumSongAdapter = new ArtistSongAlbumSongAdapter(getApplicationContext(), ArtistSongAlbumSongList);
  
      artistSongAlbumSongAdapter.onItemClickListener(new ArtistSongAlbumSongAdapter.ArtistSongAlbumSongListener() {
          @Override
          public void onClickListener(SongInfoModel songInfoModel, int position, RelativeLayout relativeLayout, View view) {
              MainActivity.setsongText(songInfoModel);
              MainActivity.ButtonPlay();
              MainActivity.PauseImage();
  
              changeSelectedSong(position);
              prepareSong(songInfoModel);
  
          }
  
          @Override
          public void onLongClickListener(SongInfoModel songInfoModel, int position, RelativeLayout relativeLayout, View view) {
  
          }
      });
  
      recyclerView_artistalbumsongs.setAdapter(artistSongAlbumSongAdapter);
  
  
      player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
          @Override
          public void onPrepared(MediaPlayer mediaPlayer) {
  
              togglePlay(mediaPlayer);
  
          }
      });
  
      player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
          @Override
          public void onCompletion(MediaPlayer mediaPlayer) {
              onSongCompletion1(mediaPlayer);
          }
      });
  
  
  
  
  }
  
  
  
  public void prepareSong(SongInfoModel song) {
  
      player.reset();
  
  
      try {
          player.setDataSource(song.getData());
          player.prepareAsync();
      } catch (IOException e) {
          e.printStackTrace();
      }
  
  }
  
  
  private void togglePlay(MediaPlayer mp) {
  
      if (mp.isPlaying()) {
          mp.stop();
          mp.reset();
  
      } else {
  
          mp.start();
  
  
          MainActivity.Handler(mp);
  
  
      }
  
  
  }
  
  private void changeSelectedSong(int index){
    //  artistSongAlbumSongAdapter.notifyItemChanged(artistSongAlbumSongAdapter.getSelectedPosition());
      currentIndex = index;
      artistSongAlbumSongAdapter.setSelectedPosition(currentIndex);
    //  artistSongAlbumSongAdapter.notifyItemChanged(currentIndex);
  
  }
  
  
  
  
  private void onSongCompletion1(MediaPlayer mediaPlayer) {
  
  
      if(currentIndex + 1 &lt; ArtistSongAlbumSongList.size()){
          SongInfoModel next  = ArtistSongAlbumSongList.get(currentIndex +1);
          changeSelectedSong(currentIndex + 1);
          prepareSong(next);
          MainActivity.setsongText(next);
      }else{
  
          SongInfoModel next1  = ArtistSongAlbumSongList.get(0);
          changeSelectedSong(0);
          prepareSong(ArtistSongAlbumSongList.get(0));
          MainActivity.setsongText(next1);
      }
  
  }
  </code></pre>
  
  <p>Singleton class:</p>
  
  <pre><code>public class MyMediaPlayer extends MediaPlayer  {
  
  private static MyMediaPlayer mpclass ;
  
  
  
  
  private MyMediaPlayer() {
  
  }
  
  public static MyMediaPlayer getInstance() {
      if (mpclass == null) {
          synchronized (MyMediaPlayer.class) {
              if (mpclass == null) {
                  mpclass = new MyMediaPlayer();
              }
          }
      }
  
      return mpclass;
  }
  </code></pre>