首页 > 解决方案 > Activity完成后如何在后台运行计时器然后再次继续

问题描述

如何将计时器保存在 sharedpreferences 中,然后在活动重新启动时再次获取

new CountDownTimer(300000,1000){

            @Override
            public void onTick(long millisUntilFinished) {
                timer.setText("Time Left: "+String.format("%d : %d min(s)",
                        TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
            }

            @Override
            public void onFinish() {
                timer.setVisibility(View.GONE);
            }
        }.start();

sharedpreferences 类中的变量是什么?

public static final long OrderTimeLeft = 300000;

标签: javaandroidsharedpreferencescountdowntimer

解决方案


更新

保持计时器在后台运行

这个结果可以很容易地通过一个简单的技巧来实现。您只需要存储计时器的开始时间。

long startTime; // Global variable

startTime = System.currentTimeMillis(); // save the time in preference
new CountDownTimer(300000,1000){
//.......
}

恢复之前

// retrieve the startTime from preference
// now calculate the remaining time 
long remainingTime = 300000 - System.currentTimeMillis() - startTime
// start your counter from here

旧答案

您需要存储来自计时器的剩余时间。

long remainingTime; // Global variable

new CountDownTimer(300000,1000){
    @Override
    public void onTick(long millisUntilFinished) {
        remainingTime = 300000 - millisUntilFinished;
//.......
}

onPause()将此值存储在 sharedPref 中并onResume()检索该值并使用该值启动您的计时器


推荐阅读