我目前正在做我的项目,想为我的Android数独游戏添加一个计时器。我需要知道源代码以及如何将源代码放入我的数独游戏中。请帮忙,我很急需要 :(
我目前正在做我的项目,想为我的Android数独游戏添加一个计时器。我需要知道源代码以及如何将源代码放入我的数独游戏中。请帮忙,我很急需要 :(
如果您正在使用 Android 并需要一个每秒钟都会“滴答”声的计时器,您可以创建以下的CountDownTimer
子类。它可以轻松地修改为以任何间隔进行“滴答”声。
如果你在android上需要每秒滴答一次的计时器,你可以创建下面的CountDownTimer
子类。它可以很容易地修改为以任何你想要的间隔来滴答。
import android.os.CountDownTimer;
public abstract class CountUpTimer extends CountDownTimer {
private static final long INTERVAL_MS = 1000;
private final long duration;
protected CountUpTimer(long durationMs) {
super(durationMs, INTERVAL_MS);
this.duration = durationMs;
}
public abstract void onTick(int second);
@Override
public void onTick(long msUntilFinished) {
int second = (int) ((duration - msUntilFinished) / 1000);
onTick(second);
}
@Override
public void onFinish() {
onTick(duration / 1000);
}
}
然后像这样使用它
CountUpTimer timer = new CountUpTimer(30000) {
public void onTick(int second) {
timerView.setText(String.valueOf(second));
}
};
timer.start();
timer.cancel()
- Dan AndreassonCountDownTimer
应该符合您的需求。文档还提供了一个小例子,可以帮助您。Chronometer
将是最容易的选择。Chronometer
有一个start()
方法,例如可以在您的Activity
的onCreate()
中调用。 - Ovidiu Latcu_countTimer = new CountDownTimer(40000, 1000) {
public void onTick(long millisUntilFinished) {
String _millis=String.valueOf(40-(millisUntilFinished/1000));
CameraScreen._timerTxt.setText("0."+_millis);
}
_countTimer.start();
import android.os.CountDownTimer
abstract class CountUpTimer(private val secondsInFuture: Int, countUpIntervalSeconds: Int) : CountDownTimer(secondsInFuture.toLong() * 1000, countUpIntervalSeconds.toLong() * 1000) {
abstract fun onCount(count: Int)
override fun onTick(msUntilFinished: Long) {
onCount(((secondsInFuture.toLong() * 1000 - msUntilFinished) / 1000).toInt())
}
}
以下是如何使用它的步骤
val counter = object: CountUpTimer(30, 1){
override fun onCount(count: Int) {
Log.i("Counter", "Counting: $count")
}
override fun onFinish() {
Log.i("Counter", "Counting done")
}
}
counter.start()
private fun stopwatch() {
var num : Long = 0L
val timer : Timer = Timer()
val tt : TimerTask = object : TimerTask(){
override fun run() {
num+=1000L
println(TimerUtil.timerDisplay(num))
}
}
timer.schedule(tt, 0L, 1000L)
}
将字符串格式化为MM:SS格式的辅助函数:
class TimerUtil {
companion object {
fun timerDisplay(time: Long): String {
val minutes = TimeUnit.MILLISECONDS.toMinutes(time)
val seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit
.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))
return " %02d:%02d".format(minutes, seconds)
}
}
}
原来,计时器在内部使用了一种称为 "system.elapsedRealTime" 的东西,它是从手机首次启动开始计算的时间。
在实际情况中,当手机关机时,即使之前保存了时间,计时器读数也会出现错误。