简体   繁体   中英

How to play bgm in my app using Service or MediaPlayer?

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM