哪种方法最适合在10秒后自动停止媒体播放?

时间:2017-01-19 03:17:18

标签: android countdowntimer android-handler

我正在使用Android 6.0并播放默认音乐。播放10秒后音乐必须自动停止。这是我的功能

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;
     }
}

效果很好,但是当我在10秒钟内调用playSound()两次时,停止时间(10秒)会在更短的时间内运行。因此,我认为Handler在我的情况下并不好。你认为计时器更好吗?或者,当我调用playSound函数时,是否需要停止处理程序。谢谢大家

我没有使用Handler,而是使用计时器作为

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

1 个答案:

答案 0 :(得分:0)

尝试使用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);
}