我有一个 CountdownTimer 从 60 秒开始倒计时。这个 CountdownTimer 通过将 textView 设置为剩余的毫秒来工作,但是每当我旋转我的设备时,CountdownTimer 都会重置。
我知道发生这种情况是因为 Activity 在轮换时重新启动。所以我尝试保存捆绑包中剩余的时间,然后在 Activity 重新启动后恢复它。
long transferValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playtimemode);
Log.d("Debug", "onCreate: " + transferValue);
long setTime = 60000;
long difference = setTime - transferValue;
new CountDownTimer(difference, 1000) {
public void onTick(long millisUntilFinished) {
millisUntilFinishedToSave = millisUntilFinished;
tvCountdown.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
tvCountdown.setText("done!");
}
}.start();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong("millisKey", millisUntilFinishedToSave);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
transferValue = savedInstanceState.getLong("millisKey");
Log.d("Debug", "onRestoreInstanceState(): " + transferValue);
}
然而这不起作用。我在这段代码的顶部初始化 transferValue(因此它返回 0),但是我怎样才能将数据从 savedInstanceState 保存到 CountdownTimer?
07-06 20:21:30.038: D/Debug(28995): onCreate: 0
07-06 20:21:30.043: D/Debug(28995): onRestoreInstanceState(): 55994