Android: Mediaplayer plays multiple times if I keep on pressing the back button and launch the app again

荒凉一梦 提交于 2019-12-25 08:33:59

问题


When I play my song and press the back button to return to return to home, the music continues playing. When I launch the app again, the music plays twice. I think it's the onResume method because I commented out the method and the problem stopped. How do I get onResume work properly? I tried using if(backgroundMusic.isplaying()) inside the onResume, but the app crashes when I resume from another activity. What am I doing wrong?

//global mediaplayer
MediaPlayer backgroundMusic;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);  
    loadBackgroundMusic();

}

private void loadBackgroundMusic() {

    //load mp3 into object and start it
    backgroundMusic = MediaPlayer.create(this,R.raw.backgrounmusic);
    backgroundMusic.setLooping(true);
    backgroundMusic.start();

}
        @Override
        protected void onPause() {
            super.onPause();
            backgroundMusic.release();

        }

        @Override
        protected void onResume() {
            super.onResume();
            loadBackgroundMusic();

        }

        @Override
        protected void onStop() {
            super.onStop();
            backgroundMusic.release();
        }

回答1:


I'm not really sure about the behavior you want. As I see it, it's one of two:

  1. Music should be played only while my Activity is visible

    If this is the case, you should look closer on the documentation for the Activity Lifecycle. This will for example tell you that onResume() will also be called the first time the Activity is created.

    So the solution would be to start the music in onResume() and stop on onPause() or similar.

  2. After starting my activity once, music should be played even if i return to home screen

    In this case you really want a Service.



来源:https://stackoverflow.com/questions/9420100/android-mediaplayer-plays-multiple-times-if-i-keep-on-pressing-the-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!