Search code examples
androidonclickonresumeonpause

How to onResume properly


I've created a simple app that has two buttons that will play and stop a song. Everything is working as it should.

However I want it to pause the song when the app goes onPause and Resume playing the song when the app is up again.

I have tried:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    mp.start();
}

But that starts the song automatically when the app starts the first time. And it also messes up the app when you click play, the song hacks and the app crashes.

Here is the onPause and onDestroy:

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    mp.pause();
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    mp.stop();
    mp.release();
} }

Solution

  • Try the below code

    @Override
    protected void onResume() {
        super.onResume();
        if (mp != null && mp.getCurrentPosition() > 0) {
            mp.start();
        }
    }