当我旋转屏幕时,计时器被销毁而不会重新创建。出于某种原因,在活动生命周期中,计时器在屏幕旋转后不会恢复到其状态。
@Override
public void onStart(){
super.onStart();
Log.d(CLASS_NAME, "onStart");
if (timerRunning) {
Log.d(CLASS_NAME,"This should give a new handler and UPDATE TIMER");
handler = new Handler();
updateTimer = new UpdateTimer();
handler.postDelayed(updateTimer, UPDATE_EVERY);
}
}
我认为问题可能是当屏幕旋转时活动被销毁时,timerRunning变为false,因此它永远不会到达onStart()中的if语句。
@Override
public void onPause(){
super.onPause();
Log.d(CLASS_NAME, "onPause");
}
@Override
public void onResume(){
super.onResume();
Log.d(CLASS_NAME, "onResume");
enableButtons();
Log.d(CLASS_NAME, "re-setting time display");
setTimeDisplay();
}
@Override
public void onStop(){
super.onStop();
Log.d(CLASS_NAME, "onStop");
if (timerRunning){
Log.d(CLASS_NAME, "HERE ON STOP SHOULD REMOVE CALLBACKS");
handler.removeCallbacks(updateTimer);
updateTimer = null;
handler = null;
}
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy");
}
@Override
public void onRestart(){
super.onDestroy();
Log.d(CLASS_NAME, "onRestart");
}
class UpdateTimer implements Runnable {
public void run() {
//Log.d(CLASS_NAME, "run");
setTimeDisplay();
if (handler != null) {
handler.postDelayed(this, UPDATE_EVERY);
}
}
}
当我旋转屏幕时,生命周期如下所示:
Clicked Start Button
Set Buttons Enabled/Disabled
//Rotate screen
onPause
onStop
HERE ON STOP SHOULD REMOVE CALLBACKS
onDestroy
Set Buttons Enabled/Disabled
Setting Text
onStart
onResume
Set buttons enabled/disabled
re-setting time display
当我想要onResume时似乎会调用onDestroy?
答案 0 :(得分:0)
当手机旋转android时,Dude会破坏你的应用并再次重新创建它......在这里你是对的。然而,当发生这种情况时,系统将调用onSaveInstanceState()方法,因此您可以在此处保存所有当前实例,然后将它们返回到Create()方法
示例:
// to save instance before your activity is destroy
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
{
savedInstanceState.putBoolean("yourKey", timerRunning );
}
}
}
//然后在onCreate()方法上检索它 if(savedInstanceState!= null){
// Restoring all Instances
timerRunning = savedInstanceState.getBoolean("yourKey");
}
但如果您不喜欢这种方法,您可以随时将您的活动设置为不在onConfiguration Change中重新创建自己,方法是在您的活动元素内的清单中添加:android:configChanges="orientation|keyboardHidden|screenSize"
,此方法也将解决您的问题并保存您一段时间编码:)
希望有所帮助