简体   繁体   中英

Java: Android: MediaPlayer sometimes returning null onResume

I'm trying to get music to play on my app but I've hit a problem which I can't figure out. When I first load the program, it works fine and the music loads and plays. If I let the phone idle and then come back to it, the app works again. But the third time I let it idle and return, the mediaplayer will return a null and crash the app on resuming. Here is the code for the mediaplayer:

    public void startMusic(Context context)
{           
    if (music != null){
        if (music.isPlaying()){
            music.stop();
        }
        music.release();
        music = null;
    }

    music = MediaPlayer.create(context, R.raw.song);

    music.setLooping(true);
    musicPlaying = true;   
}

The app will crash when it hits the music.setLooping(true); line of code, saying that music is null.

Any ideas?

It turns out I was releasing the music in the wrong place. I was doing it in the view, when I should have been doing it in the activity.

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