Syrrea Lee
Syrrea Lee

Reputation: 101

Stop playing the previous sound when another sound plays

I have a problem regarding playing a sound in an activity, I have alarm manager and I use media player to play sounds, now when I try to set two alarms (assume that these two has only 1 minute difference from their time) when the first alarm alarms and I don't close that activity then waiting for another minute another activity pops out then plays the sound too so there's two sounds playing in background.

I want to make the previous activity's sound stop when another alarms on front

Upvotes: 1

Views: 1022

Answers (1)

Opiatefuchs
Opiatefuchs

Reputation: 9870

In your manifest put this attribute into activity:

<activity
    android:name=".YourActivity"
    android:launchMode="singleTop">

What the launchMode means and which possible states there are, see here in the docs: https://developer.android.com/guide/topics/manifest/activity-element.html

Then your activity will only be started once. If it is already started, it just comes to foreground and no second one comes up. For MediaPlayer:

if(mediaPlayer!=null){

   if(mediaPlayer.isPlaying()){

         mediaPlayer.stop();
         mediaPlayer.release();
    }


     mediaPlayer = MediaPlayer.create(this, R.raw.your_sound);
     mediaPlayer.start();
}

Be sure that you don´t call mediaPlayer.isPlaying() if you have released the mediaPlayer before. This will throw an illegalStateException. This is just from scratch, you have to adjust it to your needs.

Upvotes: 0

Related Questions