我怎样才能在进入另一个 Activity 后保持我的计时器的值恢复,我的问题是如果我切换到另一个 Activity 我想使用 sharedpreference
但它不会设置为默认值帮助,因为我需要它在后台保持递减。
public void reset()
{
countDownTimer.cancel();
}
private void setTimer() {
int time = 5;
if(countDownTimer==null)
{
totalTimeCountInMilliseconds = 60 * time * 1000;
}
else
{
reset();
totalTimeCountInMilliseconds = 60 * time * 1000;
}
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
//@Override
public void onTick(long leftTimeInMilliseconds) {
seconds = leftTimeInMilliseconds / 1000;
textViewShowTime.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
@Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
}
}.start();
}
最佳答案
您应该在 onPause
中停止您的 CountDownTimer
并在 onResume
中重新启动,您的 textViewShowTime
可能无效你的 Activity 在后台。
如果你需要每 500 毫秒调用一些代码,无论你在做什么 Activity ,然后考虑使用 AlarmManager
。
关于android - 保持计时器在后台滴答作响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20953047/