【发布时间】:2019-07-11 22:12:27
【问题描述】:
当我旋转时,会调用 onCreate 方法,所以我会丢失所有的变量,这就是我想要恢复 CountDownTimer 对象的原因。 CDT 对象的 onTick 和 onFinish 回调方法在 countdownTimer 继续运行时处于活动状态。我认为解决方案是使对象可解析,但我没有设法完成我的代码
我不想使用服务,因为 Android 文档在使用服务时是特别的,我认为在我的情况下我不需要服务
//my try to make parsable the CDT object
public class MyCountDownTimer implements Parcelable {
private CountDownTimer t;
public final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public MyCountDownTimer createFromParcel(Parcel in) {
return new MyCountDownTimer(in);
}
public MyCountDownTimer[] newArray(int size) {
return new MyCountDownTimer[size];
}
};
private MyCountDownTimer(Parcel in) {
t = (CountDownTimer) in.readParcelable(Timer);
}
MyCountDownTimer(CountDownTimer t)
{
this.t =t;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
}
}
//declaretion
private CountDownTimer Timer;
protected void onSaveInstanceState(@NonNull Bundle outState){
super.onSaveInstanceState(outState);
outState.putSerializable(COUNTDOWN,new MyCountDownTimer(Timer));
}
//on restore
Timer = (CountDownTimer) savedInstanceState.getParcelable(COUNTDOWN);
//when call Timer
private void setTimer(long mTimeLeftInMillisfun){
Timer = new CountDownTimer(mTimeLeftInMillisfun,1000) {
@Override
public void onTick(long l) {
textTimer.setText("Remain "+ l/1000+" Seconds");
}
@Override
public void onFinish() {
//do sth
}
}.start();
}
【问题讨论】:
-
您要保存
CountDownTimer对象还是只保存CountDownTimer中的数据?如果只是数据,你不需要让你的类实现Parcelable
标签: android bundle parcelable countdowntimer onsaveinstancestate