Android:旋转后如何还原已停止计时码表的状态?
作者:互联网
我这样做是为了保存状态并在计时器运行时旋转后恢复状态.
Android_Chronometer pause
当我在Xsec处停止计时器,然后在Y秒之后,我改变了方向,天文台将标记为X Y秒.
无论走了多少时间,我都希望将计时器停止运转的时间保持在旋转之前.我应该怎么做?
解决方法:
我对计时表类以及如何适应方向变化也有类似的疑问.尽管有几个有用的帖子和示例,但我发现没有一个解决了整个问题.
这是一个非常有用的帖子,这里是Android_Chronometer pause,它有助于说明需要保存elapsedTime以便恢复计时.
但是,本文并未讨论如何使Chronometer幸免于Android生命周期方向变化.在计时器运行与暂停之间,经过时间的处理方式略有不同.
这是我将所有内容组合在一起的原因-在一个不错的班级中,暂停,恢复,重置,保持正常的状态:
public class ChronometerWithPause extends Chronometer {
private long timeWhenStopped = 0;
private boolean isRunning = false;
private final String getTimeKey() {
return "KEY_TIMER_TIME" + getId();
}
private final String getIsRunningKey() {
return "KEY_TIMER_RUNNING" + getId();
}
public ChronometerWithPause(Context context) {
super(context);
}
public ChronometerWithPause(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ChronometerWithPause(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void start() {
setBase(SystemClock.elapsedRealtime() - timeWhenStopped);
isRunning = true;
super.start();
}
@Override
public void stop() {
isRunning = false;
timeWhenStopped = SystemClock.elapsedRealtime() - getBase();
super.stop();
}
public void reset() {
stop();
isRunning = false;
setBase(SystemClock.elapsedRealtime());
timeWhenStopped = 0;
}
public boolean isRunning() {
return isRunning;
}
public long getCurrentTime() {
return timeWhenStopped;
}
public void setCurrentTime(long time) {
timeWhenStopped = time;
setBase(SystemClock.elapsedRealtime() - timeWhenStopped);
}
public void saveInstanceState(Bundle outState) {
if (isRunning) {
timeWhenStopped = SystemClock.elapsedRealtime() - getBase();
}
outState.putLong(getTimeKey(), getCurrentTime());
outState.putBoolean(getIsRunningKey(), isRunning());
}
public void restoreInstanceState(Bundle inState) {
isRunning = inState.getBoolean(getIsRunningKey());
setCurrentTime(inState.getLong(getTimeKey()));
timeWhenStopped = SystemClock.elapsedRealtime() - getBase();
if (isRunning) {
super.start();
}
}
}
请注意,您可以像这样在onSaveInstanceState()和onCreate()中使用它:
protected void onSaveInstanceState(Bundle outState) {
...
timer.saveInstanceState(outState);
...
然后在onCreate中,您可以使用以下方法还原计时器功能:
if (savedInstanceState != null) {
// . . .
timer.restoreInstanceState(savedInstanceState);
// . . .
}
标签:chronometer,android 来源: https://codeday.me/bug/20191011/1894726.html