Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop MediaPlayer sound while the App is closed/minimized?

In my stopwatch app, the start button is supposed to start sound and the Pause button is supposed to stop the sound. Upto this scenerio, my program works fine.

But during playing the sound, if I go back or minimize the app , the sound doesn't stop. It keeps playing (all the time, even the device is idle). And the strange thing is that when I reopen the app to stop the sound it never gets stopped. How to solve this?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timerValue = (TextView) findViewById(R.id.timerValue);

    startButton = (Button) findViewById(R.id.startButton);
    mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
    startButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            startTime = SystemClock.uptimeMillis();
            customHandler.postDelayed(updateTimerThread, 0);

               mp.start();
                mp.setLooping(true);


        }
    });

    pauseButton = (Button) findViewById(R.id.pauseButton);

    pauseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            timeSwapBuff += timeInMilliseconds;
            customHandler.removeCallbacks(updateTimerThread);
            if(mp.isPlaying())
            {
                mp.pause();

            }
       }
    });
    resetButton = (Button) findViewById(R.id.reset);


    resetButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            timerValue.setText("" + 00 + ":"
                    + String.format("%02d", 00) + ":"
                    + String.format("%03d", 00));
            startTime = SystemClock.uptimeMillis();
            timeSwapBuff = 0;

        }
    });

}

private Runnable updateTimerThread = new Runnable() {

    public void run() {

        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

        updatedTime = timeSwapBuff + timeInMilliseconds;

        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs) + ":"
                + String.format("%03d", milliseconds));
        customHandler.postDelayed(this, 0);
    }

};
like image 208
Riyana Avatar asked Dec 13 '25 17:12

Riyana


1 Answers

You can use Android lifecycle.

I think you can call mp.pause(); on onStop() and onDestroy()

sample code:

@Override
    protected void onStop() {
        super.onPause();
        mp.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mp.pause();
    }
like image 171
bjiang Avatar answered Dec 15 '25 08:12

bjiang