//应用程序启动后的时间计数器,后台任务
private long mStartTime = 0L;
//私人长mPauseTime = 0L;
private TextView mTimerLabel;
//处理定时器任务消息的处理程序
private Handler mHandler = new Handler();
static final int UPDATE_INTERVAL = 1000;
String timerStop1;
@Override
public void onCreate(Bundle savedInstanceState) {
mTimerLabel = (TextView) findViewById(R.id.textTimer);
if(mStartTime == 0L){
mStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
timerPauseButton.setTag(1);
timerPauseButton.setText("Pause");
final Button timerPauseButton = (Button) findViewById(R.id.btnTimerPause);
timerPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
// ChangeButtonText
final int status =(Integer) view.getTag();
if(status == 1) {
mHandler.removeCallbacks(mUpdateTimeTask);
mTimerLabel.setText(timerStop1);
timerPauseButton.setText("Resume");
view.setTag(0); //resume
} else{
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
timerPauseButton.setText("Pause");
view.setTag(1); //pause
}
}
});
}
// OnCreate结束
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;
mTimerLabel.setText("" + minutes + ":"
+ String.format("%02d", seconds));
timerStop1 = minutes + ":"
+ String.format("%02d", seconds);
mHandler.postDelayed(this, 200);
}
}
};
为什么我点击暂停按钮,但计时器也会在后台运行?我在5秒后点击3秒暂停点击暂停的示例我点击恢复但是它继续以8秒而不是3秒继续? 感谢
答案 0 :(得分:0)
SystemClock.uptimeMillis()
时钟会继续运行。您只能在mStartTime
中捕获一次开始时钟时间,因此当前upTimeMillis()
和mStartTime
之间的差异会增大。暂停只会停止将时间差格式设置为mUpdateTimeTask
的{{1}}。