我在活动中创建了一个计时器,有时它可以完美运行,但有时它的运行速度比指定的执行周期快。这是我的代码
public void StartTimer()
{try
{
// Start Timer
Log.e("", "time1 : " + AppConstants.TOTALTIME);
int millisUntilFinished = Integer.parseInt(AppConstants.TOTALTIME) * 60000;
final String hh = String.format("%02d",(int) ((millisUntilFinished / (1000 * 60 * 60)) % 24));
final String mm = String.format("%02d", (millisUntilFinished / 60000) % 60);
final String ss = (String.format("%02d",(millisUntilFinished % 60000 / 1000)));
Log.e("", "time : " + hh + ":" + mm + ":" + ss);
txtTime.setText(hh + ":" + mm + ":" + ss);
txtTimeSpent.setText("00:00:00");
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (txtTimeSpent.getText().toString().trim().equalsIgnoreCase(hh + ":" + mm + ":" + ss))
{
if (t != null)
t.cancel();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a");
String enddate = sdf.format(c.getTime());
AppConstants.ENDTIME = enddate;
Intent intent = new Intent(act,TestSubmissionActivity.class);
startActivity(intent);
finish();
}
else
{
txtTimeSpent.setText(" "
+ String.format("%02d", hrSpent) + ":"
+ String.format("%02d", minSpent) + ":"
+ String.format("%02d", secSpent));
AppConstants.TIMETAKEN = txtTimeSpent.getText().toString().trim();
secSpent++;
if (secSpent == 60)
{
txtTimeSpent.setText(" "
+ String.format("%02d", hrSpent) + ":"
+ String.format("%02d", minSpent) + ":"
+ String.format("%02d", secSpent));
AppConstants.TIMETAKEN = txtTimeSpent.getText().toString().trim();
secSpent = 0;
minSpent++;
if (minSpent == 60)
{
txtTimeSpent.setText(" "
+ String.format("%02d", hrSpent)
+ ":"
+ String.format("%02d", minSpent)
+ ":"
+ String.format("%02d", secSpent));
AppConstants.TIMETAKEN = txtTimeSpent.getText().toString().trim();
minSpent = 0;
hrSpent++;
}
}
CountTimeSpend++;
if(CountTimeSpend==5)
{
CountTimeSpend=0;
try {
Date d=sdfDate.parse((sdfDate.format(c.getTime())+" "+txtTimeSpent.getText().toString().trim()));
new AsyncSaveTimeSpend().execute(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
});
}
}, 0, 1000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
StartTimer() 在 AsyncTask 中被调用。这是 ondestroy()
@Override
protected void onDestroy() {
super.onDestroy();
if (t != null) {
t.cancel();
t.purge();
t = null;
}
}