gpt4 book ai didi

java - TimerTask 没有执行?

转载 作者:行者123 更新时间:2023-11-29 22:22:42 25 4
gpt4 key购买 nike

这是我的计时器类,该类旨在不断更新 View 中的计时器。但是,当我运行该应用程序时,第一条 toast 消息显示在屏幕上,但从未到达第二条消息(永远不会执行 timerTask 的“运行”方法)。我知道这可能是我做错的简单事情。如果有人能引导我朝着正确的方向前进,那就太好了。

public class MyTimer  { 

static Timer _timerTask = new Timer();
static int totalSeconds = 1, hour = 0, min = 0, sec = 0;
static String mTimeFormat = "%02d:%02d:%02d";
static String timeTakenString;



public static void start (){
Toast.makeText(GPSMain.context, "Message one", Toast.LENGTH_LONG).show();

TimerTask timer = new TimerTask() {
@Override
public void run() {
Toast.makeText(GPSMain.context, "Message two", Toast.LENGTH_LONG).show();
totalSeconds += 1;
sec += 1;
if(sec >= 60) {
sec = 0;
min += 1;
if (min >= 60) {
min = 0;
hour += 1;
}
}
timeTakenString = String.format(mTimeFormat, hour, min, sec);
postExecute.sendEmptyMessage(0); //update UI
}
private Handler postExecute = new Handler(){
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
GPSMain.timer.setText("Time Taken: "+timeTakenString);
}
};
};
_timerTask.scheduleAtFixedRate(timer,1000,1000);
}
}

调用此类的另一个文件中的代码:

MyTimer myTimer = new MyTimer();
....
myTimer.start();

项目规范已更改!我的项目负责人更改了项目规范,因此它不再需要将计时器更新到 UI,而是将其显示为最终结果。无论如何接受第一个答案,因为它解决了原始问题。将在下面发布新代码。

新代码调用:

 System.currentTimeMillis();

在运行周期的开始和结束时,返回一个 long。然后从第二个值中减去第一个值以计算执行运行周期所花费的时间量。然后对该值进行操作并将其放入计时器格式中,该格式在最后显示为字符串。

public static String getTimeTaken(long end, long start){
@SuppressWarnings("unused")
String formattedTime = "", hourHour = "", hourMin = ":", minSec = ":";
long timeTaken = (end-start)/1000, hour = 0, min = 0, sec = 0;
if (timeTaken>9 ){
hourHour = "0";
hourMin = ":0";
if (timeTaken>=60){
if (timeTaken>= 3200){
hour = timeTaken/3200;
timeTaken = timeTaken%3200;
if (hour>9){
hourHour = "";
}
}
min = timeTaken/60;
timeTaken = timeTaken%60;
if (min >9){
hourMin = ":";
}
}
sec = timeTaken;
if(sec%60<10){
minSec = ":0";
}
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}
sec = timeTaken;
minSec = ":0";
hourMin = ":0";
hourHour = "0";
return formattedTime = (hourHour+hour+hourMin+min+minSec+sec);
}

最佳答案

使用线程你不能更新你的 UI 因为你必须使用 runOnUiThread

youractivity.this.runOnUiThread(new Runnable(){public void run(){Toast.makeText(mContext, "Message", Toast.LENGTH_LONG).show();}});

关于java - TimerTask 没有执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6745876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com