开发者

Countdown timer problem on android

开发者 https://www.devze.com 2023-02-20 11:25 出处:网络
Hi I have a countdown timer in my activity oncreate method as follows start1 = new CountDownTimer(level1time, 1000)

Hi I have a countdown timer in my activity oncreate method as follows

   start1 = new CountDownTimer(level1time, 1000) 
         //timer updated every second
          {

         public void onTick(long millisUntilFinished) {
       }
    public void onFinish() {
           //switch activities
    }

          }

         .start();
    }

I then call start1.cancel later in my code. This works when this particular activity is started once but when this activity is created again later the activities switch instantly due to the first timer finishing.

My understanding is that a new timer should be created each time the activity is created but that does not seem to be the case. 开发者_如何学GoDoes anyone know how to fix this problem?


In any case it's better to use Handlers instead of Timers. I generally create a final Runnable object that has what I want run after a certain time, create a new Handler in onCreate(), and post the Runnable to it after a certain delay with postDelayed(Runnable, int). If the user leaves the activity or you ever want it to not execute, you can simply call Handler.removeCallbacks(Runnable) with your defined Runnable to stop the "timer" on it.

That's a high-level approach to your question. Get familiar with the Handler class and this becomes a very easy problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号