android 利用String.format和handler实现计时器


呃呃呃,这个实现是看到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 网上都是说是这样输出,我试了没成功报错,不知道咋玩,有知道的留个言,谢了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章