gpt4 book ai didi

android - 保持计时器在后台滴答作响

转载 作者:行者123 更新时间:2023-11-30 03:11:11 25 4
gpt4 key购买 nike

我怎样才能在进入另一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com