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

标签 android timer background count countdowntimer

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

相关文章:

android - 在 ADB 中找不到 Phone Wiko Kite

java - 聊天布局左、右与包裹背景对齐

windows - Windows 7之前的计时器合并

html - 幻灯片/旋转木马和背景 img

css - 背景 mask Facebook 个人资料预览 Popover 上的仅 CSS 技术

ios - 当我的应用程序在后台运行时,有没有办法改变一些值(value)?

Android 5.0 - 实现 Google Play 电影 Material 设计 "My movies"屏幕

android - 使用 CardsLib 库不加载带有图像的 Material 卡

jquery - 如何删除 TimeCircle 中的计数器?

python - 如何在单独运行的进程中修改类变量?