Android中使用Java的CountDownTimer [英] CountDownTimer in Android using Java

查看:53
本文介绍了Android中使用Java的CountDownTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在android中实现计时器.我正在使用倒数计时器.这是计时器代码:

I am trying to implement a timer in android. I am using the countdowntimer. Here, is the timer code:

 new CountDownTimer(totalTime * 1000, 1000) {
        @Override
        public void onTick(long l) {
            int newSec = (int) (sec - (sec - (l / 1000)));
            if(l % 60 == 0) {
                min--;
            }
            if(newSec < 10) {
                tv_timer.setText(min + ":" + z + newSec);
            } else {
                tv_timer.setText(min + ":" + newSec);
            }
        }

        @Override
        public void onFinish() {
            mediaPlayer.start();
        }
    }.start();

计时器会不断更新用户屏幕上剩余的时间.

The timer keeps updating the amount of time left on the user's screen.

问题在于计时器一直保持在00:01(1秒)结束,它从不显示00:00,并且在计时器结束后2秒响起警报音.

The problem is the timer keeps ending at 00:01 (1 second), it never displays 00:00 and the alarm tone rings 2 seconds after the timer ends.

如何在计时器结束后如何显示00:00?如何使闹钟铃声立即响起?

How can i get 00:00 to be displayed and how to get the alarm tone to ring immediately after the timer ends?

这是搜索栏代码.用户使用搜寻栏来设置计时器:

This is the seekbar code. The seekbar is used by the user to set the timer:

seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            z = 0;
            min = i / 60;
            sec = i - min * 60;
            if(sec < 10) {
                tv_timer.setText(min + ":" + z + sec);
            } else {
                tv_timer.setText(min + ":" + sec);

            }
            totalTime = i;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

推荐答案

CountDownTimer文档

onTick(long millisUntilFinished)

onTick(long millisUntilFinished)

millisUntilFinished long:直到完成为止的时间.

millisUntilFinished long: The amount of time until finished.

这意味着永远不会在您的代码中显示00:00,因为在没有时间完成时不会调用 onTick .

Which means that 00:00 won't ever be shown in your code because the onTick won't be called when there is no time left to be finished.

只需在 onFinish

@Override
        public void onFinish() {
            tv_timer.setText("00:00");
            mediaPlayer.start();
        }

关于闹钟铃声,倒数完成后似乎立即响起.您必须检查一下音调本身在一开始是否没有沉默.

About the alarm tone, seems that it rings immediately after the count down is finished. You have to check that the tone itself doesn't have a silent one or two seconds in the beginning.

这篇关于Android中使用Java的CountDownTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆