由于我的 Tabhost,无法依赖生命周期函数。
我所做的是使计时器成为中央类中的静态全局,并ontabchangedlistener
在我的 tabhost 中添加了一个用于检查被更改为的选项卡是否是带有计时器的选项卡。如果这是真的,那么它将存储计时器当前时间的 Long 值。
tabHost.setOnTabChangedListener(new OnTabChangeListener(){
@Override
public void onTabChanged(String arg0) {
// TODO Auto-generated method stub
if(arg0.contentEquals("homeGroup"))
{
//store time in centralhelper.java
//stopWatch is of type Chronometer
//stopWatchLastTime is of type Long and is initially set to zero. Chronometer uses milliseconds to determine time, will never be zero after set
CentralHelper.stopWatchLastTime = CentralHelper.stopWatch.getBase();
}
}
});
当我的 homeGroup 视图加载时,调用 onResume() 函数,这里有一个条件来检索计时器恢复计数的时间。尽管 tabhost 会在正常生命周期函数之外的每次加载中同时调用 onPause() 和 onResume(),但它们仍然在 onCreate() 之前被调用
public void onResume(){
super.onResume();
//update Chronometer with time stored in tabchangelistener
if(CentralHelper.stopWatchLastTime!=0)
CentralHelper.stopWatch.setBase(CentralHelper.stopWatchLastTime);
}
这让我可以在 onCreate() 中进行类似的检查
if(CentralHelper.stopWatchLastTime!=0)
{
CentralHelper.stopWatch.start(); //this is where it resumes counting from the base set in onResume()
}
else
{
CentralHelper.stopWatch.start();
CentralHelper.stopWatch.setBase(SystemClock.elapsedRealtime());
}