问题描述:
当通过stop()方法实现计时器暂停时,在通过start()方法继续计时的时候,会出现计时器显示的时间不是暂停前的时间。
问题分析:
查看官方API文档可以发现:
publicvoid stop ()
Added in API level 1
Stop countingup. This does not affect the base as set from setBase(long) , just the viewdisplay. This stops the messages to the handler, effectively releasing resourcesthat would be held as the chronometer is running, via start() .
stop() 方法只是停止刷新计时器的时间显示,而并没有真正停止计时。当调用 stop() 方法后,计时器还在计时,只是不再刷新界面罢了 。
那样怎么才生让计时器在恢复计时的时候能够从暂停前的时间继续计时呢?
下面有两种方法可以解决这个问题:
方法一:
开始和恢复计时:
chronometer.setBase(convertStrTimeToLong(chronometer.getText().toString())); chronometer.start();
暂停计时:
获取暂停前显示的时间并将其转换为 long 类型的时间:
protected long convertStrTimeToLong(String strTime) { String []timeArry=strTime.split(":" ); long longTime= 0 ; if (timeArry.length== 2 ) { longTime=Integer.parseInt(timeArry[0 ])* 1000 * 60 +Integer.parseInt(timeArry[ 1 ])* 1000 ; }else if (timeArry.length== 3 ){ longTime=Integer.parseInt(timeArry[0 ])* 1000 * 60 * 60 +Integer.parseInt(timeArry[ 1 ]) *1000 * 60 +Integer.parseInt(timeArry[ 0 ])* 1000 ; } return SystemClock.elapsedRealtime()-longTime; }
方法二:
private Chronometer recordChronometer; private long recordingTime = 0 ; public void onRecordStart() { recordChronometer.setBase(SystemClock.elapsedRealtime() - recordingTime); recordChronometer.start(); } public void onRecordPause() { recordChronometer.stop(); recordingTime = SystemClock.elapsedRealtime()- recordChronometer.getBase(); } public void onRecordStop() { recordingTime = 0 ; recordChronometer.setBase(SystemClock.elapsedRealtime()); }
原文链接:http://blog.youkuaiyun.com/fengyuzhengfan/article/details/38535743