由於項目的運動模塊在開始運動的時候會有一個計時器,來統計本次運動的時長,在此分享一個簡單計時器的實現方式,主要通過Handle的postDelay方法來實現一個定時任務。
/*****************計時器*******************/ private Runnable timeRunable = new Runnable() { @Override public void run() { currentSecond = currentSecond + 1000; timerText.setText(TimeUtil.getFormatHMS(currentSecond)); if (!isPause) { //遞歸調用本runable對象,實現每隔一秒一次執行任務 mhandle.postDelayed(this, 1000); } } }; //計時器 private Handler mhandle = new Handler(); private boolean isPause = false;//是否暫停 private long currentSecond = 0;//當前毫秒數 /*****************計時器*******************/
TimeUtil工具類的方法:
/** * 根據毫秒返回時分秒 * @param time * @return */ public static String getFormatHMS(long time){ time=time/1000;//總秒數 int s= (int) (time%60);//秒 int m= (int) (time/60);//分 int h=(int) (time/3600);//秒 return String.format("%02d:%02d:%02d",h,m,s); }