Reputation: 11
im a beginner and im trying to make a music player app and this code is from the now playing screen's java file
here, the true part of the code runs when i come to this activity by pressing on a bottom now playing bar and the false part is when i come to this activity by clicking on a new song from the list...
now while im on this now playing screen by clicking on a song the mediaplayer works fine but when i press back and come to the same activity by pressiing on the bottom bar
the mediaplayer says song is not playing (But the song is playing) how to fix this???
mediaPlayer = new MediaPlayer();
if(SongName == CurrentSong) //when bottom bar now playing is clicked
{
if(mediaPlayer.isPlaying())
{
Toast.makeText(getContext(), "song is still playing", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(), "song is not playing", Toast.LENGTH_SHORT).show();
}
}
else //when new song from list is clicked
{
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getContext(), Uri.parse(currentData));
mediaPlayer.prepare();
mediaPlayer.start();
}
Upvotes: 1
Views: 899
Reputation: 4035
It could be because when you reopen the activity you create a new instance of media player which is null and not playing, and you lose the reference for the active mediaplayer.
For that keep a reference to your active mediaplayer
like this:
1) Make a class:
public class ActiveMedia{
public static List<MediaPlayer> mediaPlayers = new ArrayList<MediaPlayer>();
}
2) When you start a mediaplayer
keep its reference in the above static list:
...............
else //when new song from list is clicked
{
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getContext(), Uri.parse(currentData));
mediaPlayer.prepare();
mediaPlayer.start();
//here add the mediaplayer instance
ActiveMedia.mediaPlayers.add(mediaPlayer);
..............
3) when you want to come back to activity check active players like this
for(MediaPlayer mediaPlayer : ActiveMedia.mediaPlayers){
if(mediaPlayer.isPlaying()){
//there is an active media player
}else{
//there is no active media player
}
//also you can stop the active mediaplayer or remove ..........
}
Upvotes: 1