问:当用户再次进入我的 Activity 时,不知道如何重新启动 CountDownTimer(一个使用 SharedPreferences 从用户离开 Activity 时剩余的最后几秒返回的 CountDownTimer)。我不知道在哪里放置 ct.start() 以免出现 NullPointerException 错误。
答案/工作代码:(感谢 Calvin)
ct=new CountDownTimer(86400000, 1000) {
public void onTick(long elapsed) {
long timer2=elapsed;
hours = timer2 / hours_in_millies;
timer2 %= hours_in_millies;
minutes = timer2 / minutes_in_millies;
timer2 %= minutes_in_millies;
seconds = timer2 / seconds_in_millies;
if(hours>=10&&minutes>=10&&seconds>=10)
time.setText(hours + ":" + minutes + ":" + seconds);
else
if (hours<10&&minutes>=10&&seconds>=10)
time.setText("0"+hours + ":" + minutes + ":" + seconds);
else
if (hours<10&&minutes<10&&seconds>=10)
time.setText("0"+hours + ":0" + minutes + ":" + seconds);
else
if (hours<=10&&minutes<10&&seconds<10)
time.setText("0"+hours + ":0" + minutes + ":0" + seconds);
else
if(hours>=10&&minutes>=10&&seconds<10)
time.setText(hours + ":" + minutes + ":0" + seconds);
else
if (hours>=10&&minutes<10&&seconds<10)
time.setText(hours + ":0" + minutes + ":0" + seconds);
else
if(hours>=10&&minutes<10&&seconds>=10)
time.setText(hours + ":0" + minutes+":" + seconds);
else if(hours<10&&minutes>=10 && seconds<10)
time.setText("0"+hours + ":" + minutes +":0"+ seconds);
}
public void onFinish()
{
time.setText("Ready!!");
time.setTypeface(tf);
}
}.start();
}
public void onResume() {
super.onResume();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
xtime = System.currentTimeMillis()-prefs.getLong("time",System.currentTimeMillis());
timer=86400000-(xtime+prefs.getLong("time2",0));
final SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time2",xtime+prefs.getLong("time2",0));
editor.commit();
ct.start();
}
public void onStop() {
super.onStop();
xtime=System.currentTimeMillis();
SharedPreferences.Editor editor2 = prefs.edit();
editor2.putLong("time",xtime);
editor2.commit();
ct.cancel();
}