在后台保持定时器滴答

时间:2014-01-06 15:16:14

标签: android timer background count countdowntimer

如何在转到另一个活动后保持我的计时器的值恢复,我的问题是,如果我切换到另一个我想使用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();

    }

1 个答案:

答案 0 :(得分:1)

您应该在CountDownTimer中停止onPause并在onResume重新开始,当您的活动在后台时,您的textViewShowTime可能无效。

如果您需要每500毫秒调用一些代码,无论您从事什么活动,请考虑使用AlarmManager