我知道timer.cancel()用于停止倒数计时器我也知道一旦活动进入后台,它就会调用方法
protected void onPause();
当它即将到达前景时,它会调用方法
protected void onResume();
在活动进入后台时,我一直存在一些难以存储倒数计时器的值,并且在活动再次进入后立即继续计时器。看看我尝试了什么
@Override
public void onPause() {
super.onPause();
if (mCountDownTimer != null){
mCountDownTimer.cancel();
mCountDownTimer = null;
SharedPreferences sharedPrefs = context.getSharedPreferences(TIME_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("time", mTextField.getText().toString()).commit();
}}
然后这个:
@Override
public void onResume() {
super.onResume();
SharedPreferences sharedPrefs = context.getSharedPreferences(TIME_PREF, MODE_PRIVATE);
String prefString = sharedPrefs.getString("time", null);
if (prefString != null) {
mTextField.setText(prefString);
countdown(prefString, sec);
SharedPreferences sharedPrefToDel = context.getSharedPreferences(TIME_PREF, MODE_PRIVATE);
sharedPrefToDel.edit().clear().commit();
}
}
这是我的倒计时方法:
public void countdown(final String theTime, final long longVal) {
final int red = getResources().getColor(R.color.red);
mTextField = (Button) findViewById(R.id.countdown);
mCountDownTimer = new CountDownTimer(longVal, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText(theTime);
if ((millisUntilFinished / 1000) < 60) {
if (millisUntilFinished / 1000 < 10) {
mTextField.setTextColor(red);
mTextField.setText("00:0" + millisUntilFinished / 1000);
} else
mTextField.setText("00:" + millisUntilFinished / 1000);
}
if ((millisUntilFinished / 1000) >= 60 && (millisUntilFinished / 1000) < 120) {
if (((millisUntilFinished / 1000) - 60) < 10) {
mTextField.setText("01:0" + ((millisUntilFinished / 1000) - 60));
} else
mTextField.setText("01:" + ((millisUntilFinished / 1000) - 60));
}
}
public void onFinish() {
mTextField.setText("00:00");
}
}.start();
}
问题在于,只要应用程序从后台返回,计时器就会开始显示多个倒计时。我究竟需要做什么?