剛開始有大概2秒延時,怎麼回事
final TextView timeout = (TextView)grid.findViewById(R.id.timeout);
final ImageButton tock_on = (ImageButton) grid.findViewById(R.id.tock_on);
tock_on.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timeout.setText("00:00:00");
stepTimeHandler = new Handler();
startTime = System.currentTimeMillis();
mTicker = new Runnable() {
public void run() {
String content = showTimeCount(System.currentTimeMillis() - startTime);
timeout.setText(content);
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
stepTimeHandler.postAtTime(mTicker, next);
}
};
//啟動計時線程,定時更新
mTicker.run();
}
});
第一次執行時間也就是new runnalbe和執行showtimecount的時間,應該不至於這麼慢。不過如果是text偶爾跳動2秒是有可能的。先不說系統延時之類的。就從邏輯分析是有可能的
stepTimeHandler = new Handler();
startTime = System.currentTimeMillis();
mTicker = new Runnable() {
public void run() {
String content = showTimeCount(System.currentTimeMillis() - startTime);System.currentTimeMillis() 是999毫秒,相差不到1秒,顯示應該還是00:00:00
timeout.setText(content);
long now = SystemClock.uptimeMillis();//這裡比如SystemClock.uptimeMillis() 剛好過了當前秒了,是1秒001毫秒
long next = now + (1000 - now % 1000);//到這裡下次執行時間就是2秒的時候執行
stepTimeHandler.postAtTime(mTicker, next);//再加上post延時,下次顯示就是00:00:02了
}