2017-01-19 41 views
0

我正在使用Android 6.0并播放默认音乐。播放10秒后音乐必须自动停止。这是我的功能哪种方法最适合10秒后自动停止mediaplayer?

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功能时需要停止处理程序。感谢所有

而不是使用处理器的,我使用的计时器作为

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

回答

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