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();