Mediaplayer and Thread

Asked

Viewed 98 times

0

Good night,

I have an Activity in which I play a bell x times, for t time, and for that 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(); 

}

occurs that when returning from the screen of this Activity, the sound may still be playing, and then the user can enter another Activity, where can see the available bells and test them. At this point, how can I retrieve the Thread that was holding the previous ringtone and close it so that the sound of the bells on the test screen does not overlap in a "cacophony"?

NT: In the above code example I am interested that the bell repeats overriding the previous ringtone because it is the same audio file and to create the desired effect. The problem is when another Activity is called, with audio resources as well, without the sound of that Activity has ended with Thread.

Thank you

1 answer

0

I decided as follows: I declared Mediaplayer 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.