呃呃呃,這個實現是看到camera錄像時那個計時器,然後從源碼里弄出來的,直接上代碼了。
- 源碼路徑:Camera/src/com/android/camera/manager/RecordingView.java // 系統中的實現
1.計時器功能
public class TimerTest extends Activity {
private long mRecorderStartTime;
private TextView textView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_video_recorder);
textView = findViewById(R.id.tv_time_keep);
handler.postDelayed(new Runnable() {
@Override
public void run() {
mRecorderStartTime = SystemClock.uptimeMillis();
handler.sendEmptyMessage(UPDATE_TIMER);
}
},2000);
}
private static final int UPDATE_TIMER = 1;
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == UPDATE_TIMER){
long now = SystemClock.uptimeMillis();
long mDuration = now - mRecorderStartTime;
textView.setText(formatTime(mDuration,false));
handler.sendEmptyMessageDelayed(UPDATE_TIMER,1000);
}
return true;
}
});
/**
* 計時
* @param millis
* @param showMillis
* @return
*/
private String formatTime(long millis,boolean showMillis){
final int totalSeconds = (int) (millis / 1000);
final int millionSeconds = (int) ((millis / 1000) / 10);
final int seconds = totalSeconds % 60;
final int minutes = (totalSeconds / 60) % 60;
final int hours = totalSeconds / 3600;
String text = null;
if (showMillis){
if (hours > 0){
text = String.format(Locale.ENGLISH,"%d:%02d:%02d:%02d",hours,
minutes,seconds,millionSeconds);
}else {
text = String.format(Locale.ENGLISH,"%02d:%02d:%02d",
minutes,seconds,millionSeconds);
}
}else {
if (hours > 0){
text = String.format(Locale.ENGLISH,"%d:%02d:%02d",hours,
minutes,seconds);
}else {
text = String.format(Locale.ENGLISH,"%02d:%02d",minutes,seconds);
}
}
return text;
}
}
2.System.currentTimeMillis() uptimeMillis elapsedRealtime的區別
①:System.currentTimeMillis() 系統時間,也就是日期時間,可以被系統設置修改,然後值就會發生跳變。
②:uptimeMillis 自開機後,經過的時間,不包括深度睡眠的時間,適合做時間間隔計算
③:elapsedRealtime 自開機後,經過的時間,包括深度睡眠的時間,適合做時間間隔計算
3.%d %2d %02d %.2d的區別
①:%d就是普通的輸出了
String.format("%d",6) 輸出: 6
②:%2d是將數字按寬度爲2,採用右對齊方式輸出,若數據位數不到2位,則左邊補空格
String.format("%2d",6) 輸出: 6
③:%02d,和%2d差不多,只不過左邊補0
String.format("%02d",6) 輸出: 06
④:%.2d沒見過,但從執行效果來看,和%02d一樣
String.format("%.2d",6) 輸出: 06
%.2d 網上都是說是這樣輸出,我試了沒成功報錯,不知道咋玩,有知道的留個言,謝了