-4

Music does not resume after pressing home button and then pressing the app from recent list. Please make necessary changes in the code given.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onPause() {
        super.onPause();
        mySound.release();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mySound != null)
            mySound.start();
    }

    MediaPlayer mySound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mySound = MediaPlayer.create(MainActivity.this,R.raw.sleep);
        mySound.start();
        mySound.setLooping(true);
    }
}
Abbas
  • 3,529
  • 5
  • 36
  • 64

1 Answers1

1

First of all have a look at How to ask a Good Question on SO.

Secondly Have a read through How to Add code in SO.

Now to answer your question. The problem is in your Activity's onPause() method, just change it to.

@Override
protected void onPause() {
    super.onPause();
    if (mySound != null)
        mySound.pause();
}

Only ever call release() on a MediaPlayer when you no longer need it. From the Android docs

void release()

Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer.

So instead use pause()

void pause()

Pauses playback. Call start() to resume.

Have a look at the state diagram of a MediaPlayer MediaPlayer State Diagram

What the diagram represents are valid states where it is OK to use the MediaPlayer object.

Community
  • 1
  • 1
Abbas
  • 3,529
  • 5
  • 36
  • 64
  • requirements=The music should pause when i press home button and continue from where it was paused when i open the app from recent apps list. –  Oct 06 '16 at 10:01
  • @Anvaypancholiya Works for me. What do you mean when you say "not working still"? – Abbas Oct 06 '16 at 12:43
  • means the music does not resume from where ut wa closed –  Oct 06 '16 at 14:51
  • @Anvaypancholiya works for me. I get the playback onResume and playback resumes from the time I left it at. Read through the answer once more and recheck your code. If that doesn't help then post a [Minimal Complete and Verifiable Example](http://stackoverflow.com/help/mcve) that carries your problem. – Abbas Oct 07 '16 at 12:53