这是我的计时器类,该类旨在不断更新视图中的计时器。但是,当我运行应用程序时,第一个 toast 消息会显示在屏幕上,但第二个消息永远不会到达(timerTask 的“run”方法永远不会执行)。我知道这可能很简单,我做错了。如果有人能引导我朝着正确的方向前进,那就太好了。
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);
}