【问题标题】:Count up timer on Android?Android上的倒计时?
【发布时间】:2015-06-19 15:49:38
【问题描述】:

我一直在寻找一种方法来创建一个计时器,该计时器以 mm:ss:SS 的格式计数,但我一生都找不到这样做的方法。我有一个通过 Handler 和 Runnable 运行的计时器,但计时已关闭,大约需要 2.5 秒才能完成“秒”。我也需要这个计时器也能倒计时!

谁能给我任何资源或代码 sn-ps 来研究这个,因为它是我正在编写的应用程序的重要组成部分。

这是我使用的一些代码

private Handler handler = new Handler();

private Runnable runnable = new Runnable() {
       @Override
        public void run() {
      /* do what you need to do */
            testMethod();
      /* and here comes the "trick" */
            handler.postDelayed(this, 10);
        }
    };

public void testMethod()
    {
//        Log.d("Testing", "Test");
        final TextView timeLabel = (TextView)findViewById(R.id.timeString);
        count++;

        seconds = (int)(count / 100);

        final String str = ""+count;
        runOnUiThread(new Runnable() {
            public void run() {
                timeLabel.setText("" + seconds);
//                Log.d("Time", "" + count);
            }
        });
    }

塔!

【问题讨论】:

    标签: java android timer format milliseconds


    【解决方案1】:

    通过扩展 CountDownTimer 类创建小型自定义类,然后添加整数或长类型,然后递增它,因为在这种情况下每个刻度是 1 秒(整数)

    public class TimeCounter extends CountDownTimer {
        // this is my seconds up counter
        int countUpTimer;
        public TimeCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            countUpTimer=0;
        }
    
        @Override
        public void onTick(long l) {
            //since each tick interval is one second
            // just add 1 to this each time
            myTextView.setText("Seconds:"+countUpTimer);
            countUpTimer = countUpTimer+1;
        }
    
        @Override
        public void onFinish() {
            //reset counter to 0 if you want
            countUpTimer=0;           
        }
    }
    
      TimeCounter  timer = new TimeCounter(whenToStopInSeconds*1000, 1000);
    

    这应该让你开始,在你的情况下使用 long 而不是 integer countUpTimer = countUpTimer+1000countUpTimer 键入并根据您的需要进行时间解析

    【讨论】:

      【解决方案2】:

      我建议使用java.util.Timer 和java.util.TimerTask API,而不是使用处理程序。使用 Timer 的 void scheduleAtFixedRate() 方法,该方法基本上在固定时间间隔后执行任务。 Handler 的方法很可能使用固定延迟执行。

      Timer's Documentation

      TimerTask's Documentation

      【讨论】:

        猜你喜欢
        • 2012-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多