铃声无法停止



我正在开发一个速度计应用程序,现在正在研究某种速度限制功能。这个想法是当速度超过目标值时制造噪音。我使用的代码:

Ringtone ringtone;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.updateSpeed(null);
}

private void updateSpeed(Location location){
...
float speed = location.getSpeed();
int i = (int) speed;
this.doLimit(i);
}
private void doLimit(int i) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
if (i >= 50) { 
this.lets_dance();
} else {
if (ringtone.isPlaying()) {
ringtone.stop();
}
}
}
private void lets_dance() {
ringtone.play();
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
public void run(){
if(!ringtone.isPlaying()){
ringtone.play();
}
}
}, 1000, 1000);
}

问题是铃声第一次播放速度超过50,并且没有停止。

在我尝试了很多使用Mediaplayer的方法之前,有和没有setloop和情况更糟(它导致应用程序延迟,就像我在计算器上使用它一样)。

这可能是因为每次调用dollimit()时,都会创建一个新的ringtone实例。尝试在onCreate()函数中使用以下几行:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);

最新更新