简体   繁体   中英

Stop MediaPlayer in the background - Android

In one of my activity, there is a button to play music using mediaPlayer. Also it has an option to play the music in background or stop when the activity is finished.

I use this code for that.

@Override
protected void onStop() {
    super.onStop();
    SharedPreferences perfs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    if (!perfs.getBoolean("bg_play", true)) {
        mediaPlayer.stop();
        mediaPlayer.release();
    }
}

That works perfectly. Now the problem is when the user is back on the activity and press the play button, it starts a new mediaPlayer and play the new music. I want to stop the previous music running in background when new music is started.

Here is my code

private void myMediaPlayer() {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();
    }
    else {
            mediaPlayer.stop();
            mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(Environment.getExternalStorageDirectory()+"file.mp3");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();
    }
}

And the MediaPlayer declaration

MediaPlayer mediaPlayer=new MediaPlayer();

before onCreate

I'm a beginner to programing so I might be wrong. .. Wouldn't making the mefiaPlayer variable static work? But I think the problem is that when you go back to the activity, the activity is being rebuilt.

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