2017-01-19 2 views
0

J'utilise Android 6.0 et joue une musique par défaut. La musique doit automatiquement s'arrêter après avoir joué 10 secondes. Ceci est ma fonctionQuelle est la meilleure méthode pour arrêter automatiquement mediaplayer après 10 secondes?

public MediaPlayer mp = null; 
public void playSound(){ 
    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); 
    try { 
     if (mp != null && mp.isPlaying()) { 
      mp.stop(); 
      mp.release(); 
      mp=null; 
     } 
     mp = MediaPlayer.create(getApplicationContext(), notification); 
     mp.start(); 
     Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      public void run() { 
       mp.stop(); 
      } 
     }, 10000); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    @Override 
public void onDestroy() { 
     if(mp!=null && mp.isPlaying()){ 
     mp.stop(); 
     mp.release(); 
     mp=null; 
    } 
} 

Il a bien fonctionné, mais quand je l'appelle playSound() temps deux fois dans les 10 secondes, puis le temps d'arrêt (10 secondes) fonctionne en moins de temps. Par conséquent, je pense que le Handler n'est pas bon dans mon cas. Pensez-vous que le minuteur est meilleur? Ou dois-je arrêter le gestionnaire lorsque j'appelle la fonction playSound. Merci à tous

Au lieu d'utiliser Handler, j'utilise minuterie

if(mCountDownTimer_Playing!=null){ 
       mCountDownTimer_Playing.cancel(); 
       mCountDownTimer_Playing=null; 
      } 
      mCountDownTimer_Playing = new CountDownTimer(10000,1000) { 
       @Override 
       public void onTick(long millisUntilFinished) { 
       } 
       @Override 
       public void onFinish() { 
        mpCalling.stop(); 
       } 
      }; 
      mCountDownTimer_Playing.start(); 

Répondre

0

Essayez d'utiliser la place TimerTask,

public MediaPlayer mp = null; 
Timer timer = null; 
public void playSound() { 
     Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); 
     if(timer!=null){ 
      timer.cancel(); 
      timer.purge(); 
      timer=null;} 
     if (mp != null && mp.isPlaying()) { 
      mp.stop(); 
      mp.release(); 
      mp = null; 
     } 
     mp = MediaPlayer.create(getApplicationContext(), notification); 
     mp.start(); 
     timer= new Timer(); 
     timer.schedule(new TimerTask() { 
      @Override 
      public void run() { 
       mp.stop(); 
      } 
     }, 10000); 
}