I am a solo developer so I am still learning. I am trying to use Fragments for a game's menu. In the menu there is an option to preview and set background music. So in the MusicFragment I have this code:
public class MusicFragment extends Fragment {
Music music = new Music();
// more code //
private void previewSong() {
music.playSong(getActivity(), "Song_1", milliseconds)
}
private void stopSong() {
music.stopPlayer();
}
}
I have a separate class - "Music" for the music, the code is like so:
public class Music extends Activity {
MediaPlayer player;
public void playSong(Context context, String songName, int milliseconds) {
if(player == null) {
player = MediaPlayer.create(context, R.raw.song1);
player.seekTo(milliseconds);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
}
});
}
player.start();
}
public void stopPlayer() {
if(player !=null) {
player.stop();
player.reset();
player.release();
player = null;
}
}
public String playerStatus() {
if(player == null) {
return "player is null";
} else {
return "player is NOT null";
}
}
}
I can start and stop the player from the fragment with no problems. What I am trying to solve for is the occasion where the user previews the music and then closes/minimizes the app - without turning the music off (stopPlayer()) in the MusicFragment (the music still playing).
In that case the app closes but the music is still ongoing. My understanding is that fragments (in this case MusicFragment) do not have onPause(). The Main_Activity does have onPause - but when I read the MediaPlayer's status via the Main_Activity's onPause() it displays the playerStatus as "NULL" even though song1 is still playing on the device while the app is closed.
I've tried to exclude the additional Music class and just create the MediaPlayer in the MusicFragment but the result is the same. Obviously if the Fragment had an OnPause I would call the stopSong() method from there. I think I'm not understanding a fundamental concept. Any assist would be greatly appreciated.