我是Android编程的新手,在应用程序重新获得焦点后,我在我的Android应用程序中尝试恢复倒数计时器。如何获取当前状态的保存实例,当用户返回应用程序时应该恢复该状态?
这是我的代码:
private long resume_timer;
MainActivity.CounterClass count_timer;
TextView timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced);
count_timer = new MainActivity.CounterClass(180000, 1000);
count_timer.start();
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
resume_timer = millisUntilFinished;
long millis = millisUntilFinished;
String hms = String.format(Locale.getDefault(),
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
timer.setText(hms);
}
@Override
public void onFinish() {
timer.setText("time's up!!");
}
@Override
protected void onPause() {
count_timer.cancel();
super.onPause();
}
@Override
protected void onResume() {
// how do i resume timer here? this logic dot work.
count_timer = new MainActivity.CounterClass(resume_timer, 1000);
count_timer.start();
super.onResume();
}
答案 0 :(得分:0)
我通过利用活动生命周期解决了这个问题,如下所示:
private long resume_timer;
MainActivity.CounterClass count_timer;
TextView timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced);
count_timer = new MainActivity.CounterClass(180000, 1000);
count_timer.start();
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
resume_timer = millisUntilFinished;
long millis = millisUntilFinished;
String hms = String.format(Locale.getDefault(),
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
timer.setText(hms);
}
@Override
public void onFinish() {
timer.setText("time's up!!");
}
@Override
protected void onPause() {
count_timer.cancel();
super.onPause();
}
@Override
protected void onRestart() {
//resume timer when user comes back to the app
count_timer = new MainActivity.CounterClass(resume_timer, 1000);
count_timer.start();
super.onRestart();
}