为什么在处理程序上没有延迟?

时间:2020-03-20 10:58:12

标签: java android

我为警报创建了一个处理程序,该警报应激活4秒钟,停止4秒钟,然后再次激活。当我将它放在if语句中时,它不起作用;警报持续播放,停止不到一秒钟,然后继续再次激活而没有延迟。想知道是否有人知道为什么会这样,我应该怎么做才能纠正它。谢谢。

private Handler handler2 = new Handler();
private Runnable startalert = new Runnable() {
    @Override
    public void run() {
        alert2.start();
        handler2.postDelayed(this, 4000);
    }
};

@Override
public void onLocationChanged(Location location) {




    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);
            handler2.removeCallbacks(startalert);


        } else if(currentSpeed >=5.00 && currentSpeed <=9.99) {
            background.setBackgroundColor(Color.YELLOW);
            handler2.removeCallbacks(startalert);


        } else if(currentSpeed >=10.00) {
            background.setBackgroundColor(Color.RED);
            startalert.run();

        }
}

1 个答案:

答案 0 :(得分:0)

使用可运行对象代替'this'。

private Runnable startalert = new Runnable() {
    @Override
    public void run() {
        alert2.start();
        handler2.postDelayed(startalert, 4000);
    }
};

另一种方法:

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
        alert2.start(); 
        handler.postDelayed(this, 4000);
      }
    }, 4000);
相关问题