MediaPlayer and Thread

0

Good evening,

I have an activity in which I reproduce a bell x times, during t time, and for this I use a MediaPlayer inside a Thread, as below:

public void tocarSino(final int repeticao, final long intervalo,final int audio, final Context ctx){
          Thread timerSound = new Thread(){
              public void run(){
                  try {
                      for (int i=1; i<=repeticao; i++) {
                          MediaPlayer mediaPlayer = MediaPlayer.create(ctx, audio);
                          mediaPlayer.start();
                          sleep(intervalo);
                      }
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          };
          timerSound.start(); 

}

When you return from the Activity screen, the sound may still be playing, and then the user can enter another Activity, where they can see the available bells and test them. At that point, how can I retrieve the Thread that was holding the previous ring and lock it so the bells on the test screen do not overlap in a "cacophony"?

NT: In the code example above it interests me that the bell repeats overlapping the previous ring because it is the same audio file and to create the desired effect. The problem is when another activity is called, with audio capabilities too, without the sound of that activity ending with the Thread.

Thank you

    
asked by anonymous 24.01.2017 / 08:01

1 answer

0

I resolved this: I declared the MediaPlayer as global and added the following code to onPause

    @Override
protected void onPause() {
    if ((timerSound != null) && (timerSound.isAlive())){
        timerSound.interrupt();
        timerSound = null;
    }
    if((mediaPlayer != null) && (mediaPlayer.isPlaying())){
        mediaPlayer.stop();
        mediaPlayer=null;

    }
    super.onPause();
}

But I would still like to know how to recover a Thread started by an Activity from another Activity. Att.

    
25.01.2017 / 02:24