我想启动一个计数器2分钟,当活动销毁时,我想保存该计数器,然后在活动恢复时我想在我离开的地方启动计数器
counter = new CountDownTimer(120000, 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished)
{
textview.setText("" + String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
Log.i(TAG, "onTick: "+millisUntilFinished);
}
public void onFinish()
{
textview.setText("done!");
}
}.start();
答案 0 :(得分:2)
当活动被销毁时,我们只保存一个millisUntilFinished
的值,并在活动再次开始时使用该值创建一个新的CountDownTimer
。
long millisUntilFinished;
在onDestroy()
(或onStop()
)中
@Override
public void onDestroy() {
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putLong("millisUntilFinished", millisUntilFinished);
editor.apply();
super.onDestroy();
}
并在要启动millisUntilFinished
时获得CountDownTimer
的值
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
millisUntilFinished = prefs.getLong("millisUntilFinished", 120000);
counter = new CountDownTimer(millisUntilFinished, 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
this.millisUntilFinished = millisUntilFinished;
textview.setText("" + String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
- TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
Log.i(TAG, "onTick: " + millisUntilFinished);
}
public void onFinish() {
textview.setText("done!");
}
}.start();
答案 1 :(得分:2)
由于无法始终保证onStop
以onDestroy()
方法将计数器数据存储在共享首选项中,请使用onResume
方法存储的数据来启动计数器