Java 获得速度后需要帮助设置条件吗
我是个编码初学者。基本上,我正在构建一个速度计应用程序。我想设定一些条件;如果速度低于5km/h,背景为绿色,如果速度在5km/h到9km/h之间,背景为黄色,最后为红色;当速度高于10km/h时,背景将为红色,警报将激活4秒,间隔5秒 现在,当速度达到10或更高时,警报将不间断地继续播放,几秒钟后应用程序崩溃。我想知道是否有人可以帮助我解决这个问题,并帮助我编写正确的代码来实现。多谢各位Java 获得速度后需要帮助设置条件吗,java,android,android-studio,Java,Android,Android Studio,我是个编码初学者。基本上,我正在构建一个速度计应用程序。我想设定一些条件;如果速度低于5km/h,背景为绿色,如果速度在5km/h到9km/h之间,背景为黄色,最后为红色;当速度高于10km/h时,背景将为红色,警报将激活4秒,间隔5秒 现在,当速度达到10或更高时,警报将不间断地继续播放,几秒钟后应用程序崩溃。我想知道是否有人可以帮助我解决这个问题,并帮助我编写正确的代码来实现。多谢各位 @Override public void onLocationChanged(Location loca
@Override
public void onLocationChanged(Location location) {
//for alert
alert2 = MediaPlayer.create(this, R.raw.car_alarm);
CountDownTimer Timer = new CountDownTimer(4000, 4000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (alert2.isPlaying()) {
alert2.stop();
alert2.release();
}
}
};
Timer.start();
if (location == null) {
speedo.setText("-.- km/h");
} else {
currentSpeed = location.getSpeed() * 1.85f; //Knots to kmh conversion.
speedo.setText(Math.round(currentSpeed) + " km/h");
}
if (currentSpeed <=4.99) {
background.setBackgroundColor(Color.GREEN);
alert2.stop();
} else if (currentSpeed >=5.00 && currentSpeed <=9.99) {
background.setBackgroundColor(Color.YELLOW);
alert2.stop();
} else if (currentSpeed >=10.00) {
background.setBackgroundColor(Color.RED);
alert2.start();
}
}
@覆盖
已更改位置上的公共无效(位置){
//警惕
alert2=MediaPlayer.create(此为R.raw.car_报警);
倒计时计时器=新的倒计时计时器(40004000){
公共void onTick(长毫秒未完成){
}
公共无效onFinish(){
如果(alert2.isPlaying()){
警报2.停止();
警报2.释放();
}
}
};
Timer.start();
if(位置==null){
speedo.setText(“-.-km/h”);
}否则{
currentSpeed=location.getSpeed()*1.85f;//从节到公里小时的转换。
speedo.setText(数学圆整(当前速度)+“km/h”);
}
如果(currentSpeed=5.00&¤tSpeed=10.00){
背景:背景色(颜色:红色);
alert2.start();
}
}
警报持续播放,没有间隔,几秒钟后
应用程序崩溃了
不,不是这样的。但每次位置发生变化时,您都会启动计时器!因此,您有许多并行启动的计时器
你必须具体化你的计时器。对
alert2
也有同样的评论:您不必重新创建它!只需创建并重用它。这是否回答了您的问题?没有将此标记为完全重复,这只与您相关,以帮助您在将来进行调试:)