java - 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;
解决方案
更新
保持计时器在后台运行
这个结果可以很容易地通过一个简单的技巧来实现。您只需要存储计时器的开始时间。
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()
检索该值并使用该值启动您的计时器
推荐阅读
- continuous-integration - 如何使 CICD 为相互依赖的多个存储库工作
- php - PHP DOMDocument/LIBXML 替换 ( " 和 ' )
- python - 多个值 RewriteMap prg
- android - 无法从 Android 中的 TextView 获取文本
- orientdb - OrientDB 数据库可以完全加密吗?
- android - 没有来自广告服务器的填充。带广告:无法加载广告:3
- php - 获取 HTML 滑块的 post 值并基于整数分配文本值
- ios - ios-charts:轴和网格线间歇性缺失
- c++ - 执行相同功能的不同结果[C++]
- javascript - 我可以用 Jasmine 测试 setInterval 吗?