1. Android 秒表 Demo
代码主要从系统-时钟的秒表模块截取。
主要原理:View事件的PostRunable进行时间和UI的更新,不同于我们常用的Thread+延时, Handle + 延时和TimeTask定时,起码我第一次看还是觉得很神奇
2. GitHub demo下载
https://github.com/sufadi/SuStopwatch
3. 源码方法
3.1 秒表开始
主要进行秒表开始和UI的状态切换,主要核心是 mTime.post(mTimeUpdateRunnable); 进行触发
/**
* Start the stopwatch.
*/
public void doStart(View view) {
// Update the stopwatch state. 更新数据库状态
DataModel.getDataModel().startStopwatch();
// Start UI updates.
startUpdatingTime();
mTime.update();
mTimeText.blinkTimeStr(false);
// Acquire the wake lock.防止CPU休眠,导致不刷新时间
acquireWakeLock();
}
/**
* Post the first runnable to update times within the UI. It will reschedule
* itself as needed.
*/
private void startUpdatingTime() {
// Ensure only one copy of the runnable is ever scheduled by first
// stopping updates.
stopUpdatingTime();
mTime.post(mTimeUpdateRunnable);
}
3.2 设置Runnable定时
/**
* This runnable periodically updates times throughout the UI. It stops
* these updates when the stopwatch is no longer running.
*/
private final class TimeUpdateRunnable implements Runnable {
@Override
public void run() {
Log.d("suhuazhi", "TimeUpdateRunnable");
final long startTime = SystemClock.elapsedRealtime();
updateTime();
if (getStopwatch().isRunning()) {
// The stopwatch is still running so execute this runnable again
// after a delay.
final boolean talkBackOn = true;
// Grant longer time between redraws when talk-back is on to let
// it catch up.
final int period = talkBackOn ? 500 : 25;
// Try to maintain a consistent period of time between redraws.
final long endTime = SystemClock.elapsedRealtime();
final long delay = Math.max(0, startTime + period - endTime);
mTime.postDelayed(this, delay);
}
}
}
3.3 秒表暂停
核心 自定View 进行 mTime.removeCallbacks(mTimeUpdateRunnable) 即可
/**
* Pause the stopwatch.
*/
public void doPause(View view) {
// Update the stopwatch state
DataModel.getDataModel().pauseStopwatch();
// Redraw the paused stopwatch time.
updateTime();
// Stop UI updates.
stopUpdatingTime();
mTimeText.blinkTimeStr(true);
}
/**
* Remove the runnable that updates times within the UI.
*/
private void stopUpdatingTime() {
mTime.removeCallbacks(mTimeUpdateRunnable);
}
3.4 秒表的复位
记得是否CPU唤醒锁,将数据库秒表数据重新初始化即可
/**
* Reset the stopwatch.
*/
public void doReset(View view) {
// Update the stopwatch state.
DataModel.getDataModel().resetStopwatch();
// Clear the times.
mTimeText.setTime(0, true, true);
// Release the wake lock.
releaseWakeLock();
}