My APP has 3 activities named "MainActivity", "LevelActivity" and "GameActivity". Now I want to play BGM in MainActivity and LevelActivity. When I jump from Main to Level, I don't want the music to start from the beginning. So I use Service to play BGM.

But the problem is that if I don't override onStop() in MainActivity, the BGM is still playing after I clicked the "HOME" button. But if I override onStop() in MainActivity, the BGM will stop when I jump from Main to Level.

public class MusicService extends Service {
    private MediaPlayer mediaPlayer;
    @Override
    public void onCreate() {
    // my codes...
    }
    @Override
    public void onStart(Intent intent, int startId) {
    // my codes...
    }
    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        super.onDestroy();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

What should I do to stop BGM when I press "HOME"?

Thanks.

1 Answers

0
ismail alaoui On

you can do a trick by adding a boolean variable .

1- create a boolean variable isAppStillRunning = false

2- then when you want to start level activity make isAppStillRunning = true before startActivity()

3- whenever you go back to MainActivity make isAppStillRunning = false

now in onStop() in your MainActivity ,

if(!isAppStillRunning){
//do the proccess to stop music
}