user6930425
user6930425

Reputation:

Resuming music in android

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);
    }
}

Upvotes: -4

Views: 64

Answers (1)

Abbas
Abbas

Reputation: 3331

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.

Upvotes: 1

Related Questions