在MainActivity.java的顶部,我添加了:
private Handler customHandler = new Handler();
long timeSwapBuff = 0L;
然后在onCreate里面我做了:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread,0);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
customHandler.removeCallbacks(updateTimerThread);
}
});
然后在updateTimerThread:
private Runnable updateTimerThread = new Runnable() {
public void run() {
long updatedTime = 0L;
long timeInMilliseconds = 0L;
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;//System.currentTimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
现在每次从开始运行我的程序时,计时器将从00:00:00开始
现在我想以某种方式添加每一秒做某事的东西。 不要重置计时器不暂停或停止它让它继续运行,但每一秒我想在我的程序中做其他事情。
问题是如何检查每一秒做某事?