java - 我在 android studio 中制作计时器时遇到问题
问题描述
在应用程序中,我重新打开了与计时器相同的活动。第一次计时器工作,但之后它开始onFinish()
在随机时间窃听运行。我该如何解决?
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
wrongAnswer();
}
}.start();
解决方案
您必须将 CountDownTimer 存储在计时器中,并在您移动到另一个活动或片段时取消它;
创建CountDownTimer
为全局变量(在 onCreate 之上)
CountDownTimer timer;
在您想要启动计时器的地方或任何时候初始化计时器
timer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
textQuestion.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
wrongAnswer();
}
}.start();
并onDestroy
取消它
@Override
protected void onDestroy() {
if(timer != null) timer.cancel();
super.onDestroy();
}
推荐阅读
- awk - 从第一行读取变量并打印整个文件,然后打印变量
- typescript - 将对象键合并到类中
- python - 转换 .ui 文件时出错,未转换为 .py
- amazon-web-services - 删除带有引用的资源
- node.js - 关于nodejs使用'async-lock'返回值的问题
- javascript - python服务器和javascript客户端之间的Websocket
- javascript - 只能通过一种方法访问“this”
- r - 如何从 R 中的多个用户收集 Twitter 列表成员身份?
- javascript - 无法从控制器访问 NodeJS 模型类。使用 EJS
- python - 将预编译的扩展放在非纯 Python Wheel 包的根文件夹中