我基本上只是想从应用程序启动时的0:00开始跟踪秒和分钟,并在TextView中显示这样做的最佳方法是什么?
答案 0 :(得分:5)
当计时器启动非UI线程时,我宁愿不使用它来更新TextView。在您的情况下,Timer可以由Handler类替换。而且您还可以避免这个新的非UI线程的开销。 Here就是一个例子:
private Handler mHandler = new Handler();
OnClickListener mStartListener = new OnClickListener()
{
public void onClick(View v)
{
if (mStartTime == 0L)
{
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
.........
private Runnable mUpdateTimeTask = new Runnable()
{
public void run()
{
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10)
{
mTimeLabel.setText("" + minutes + ":0" + seconds);
}
else
{
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postAtTime(this,start + (((minutes * 60) + seconds + 1) * 1000));
}
};
答案 1 :(得分:3)
beginning time - current time
)我不确定从TimerTask作业更新TextView时是否会遇到问题,因为它不在UI线程中运行,在这种情况下,您可以使用Activity.runOnUiThread来执行此操作
答案 2 :(得分:2)
Runnable run = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = (seconds%3600)/60;
int hours = seconds / 3600;
seconds = seconds % 60;
et1.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et2.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
// et3.setText(String.format("%02d:%02d:%02d",hours, minutes, seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask {
public void run() {
handler.sendEmptyMessage(0);
}
};
在你的程序中试试......!