Android 如何创建无限循环

Android 如何创建无限循环,android,loops,timer,countdowntimer,Android,Loops,Timer,Countdowntimer,好的,我需要在倒计时时创建一个无限循环。我的代码是: public void countdown() { if (x != null) { x.cancel(); } x = new CountDownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() {

好的,我需要在倒计时时创建一个无限循环。我的代码是:

public void countdown() {
    if (x != null) {
        x.cancel();
    }

    x = new CountDownTimer(20000, 1000) {
        public void onTick(long millisUntilFinished) {
        }

        public void onFinish() {
            showNotification();
        }
    };
    x.start();
}

x只是一个静态倒计时变量。问题是,我尝试了许多方法使上述代码正常工作,我的意思是,当倒计时结束时,它会显示通知,它应该重新开始,等等……但我找不到方法。你可以使用while循环:
while(true){
//做事
}


当它完成了“任务”后,它将重新开始,无限

希望这对你有帮助

public void countdown(){
    if (x != null) {
        x.cancel();
    }
    x = new CountDownTimer(20000, 1000) {
       public void onTick(long millisUntilFinished) {
        }
       public void onFinish() {
           showNotification();
            x.start();
        }
    };
 }

是在计时器完成后重新启动计时器:) 像这样:

   x = new CountDownTimer(20000, 1000) {
            public void onTick(long millisUntilFinished) {
            }

            public void onFinish() {
                showNotification();
                start();// here, when your CountDownTimer has finished , we start it again :)
            }
        };
        x.start();

为什么不使用一个定时定时器呢?它将在指定的时间间隔内重复,直到调用cancel(),类似于:

public void countdown() { 
    if (x != null) {
        x.cancel();
    }

    x = new Timer("timerName");
    x.schedule(_timerTask, 0, 20000);
}

private static final TimerTask _timerTask = new TimerTask() {
    @Override
    public void run() {
        showNotification();
    }
};

为了让你的计时器继续工作,只要把

<countdowntime>.start(); 
.start();

在记录倒计时计时器的
onfinish
块中(longmillisInFuture,long倒计时间隔)

其中Long.MAX_值=9223372036854775807毫秒或约2.92亿年(多或少秒)

它不是无限的,但它非常长。

创建无限循环的简单方法: 每一个secod调用方法

new CountDownTimer(1000, 1000) 
   {
        public void onTick(long l) {}
        public void onFinish() 
        {
          //Code hear
          start();
        }
    }.start();

这将不会无限地重新启动倒计时,但它将无限地实例化并启动大量计时器,这并不是这家伙想要的:)此方法的CPU使用量很大,需要使用asynctaskthis.start();;;
new CountDownTimer(1000, 1000) 
   {
        public void onTick(long l) {}
        public void onFinish() 
        {
          //Code hear
          start();
        }
    }.start();