【问题标题】:Not able to restore saved instance of activity无法恢复已保存的活动实例
【发布时间】:2013-11-13 10:56:37
【问题描述】:

这是我的 GamePlay 活动代码

public class GamePlay extends Activity implements OnClickListener {

private boolean disableSound = false;
//.....
//Code Code
//.....

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //.....
    //Code Code
    //.....
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("disableSound", disableSound);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  disableSound = savedInstanceState.getBoolean("disableSound");
  Menu menu = (Menu)findViewById(R.menu.tic_tac_toe);
  MenuItem toggleSoundItemMenu = menu.findItem(R.id.toogle_sound_menu);
  if(disableSound)
      toggleSoundItemMenu.setTitle(R.string.toggle_sound_off_label);
  else
      toggleSoundItemMenu.setTitle(R.string.toggle_sound_on_label);

}

//other functions and code
}

现在在游戏重新开始时,我正在重新开始活动。以下代码在 onClickListener() 中,并带有适当的案例

    case R.id.game_play_restart_button:
        Intent restartActivity = new Intent(this,GamePlay.class);
        finish();
        startActivity(restartActivity);
        break;

但状态仍然不存在。我禁用声音并重新启动游戏,然后声音重新打开,这是默认行为。我错过了什么?任何建议表示赞赏。

【问题讨论】:

  • 我相信这是意料之中的。重新启动后,您的活动将被销毁并重新创建。它不会持久化状态。

标签: android android-activity savestate


【解决方案1】:

只要系统没有销毁活动,系统就会保留 savedInstanceState 包。 当您调用完成时,您会销毁当前活动以及它附带的捆绑包。 这就是你无法取回布尔值的原因。

您应该考虑将此布尔值作为额外的 Intent 传递,例如:

restartActivity.putExtra("disableSound", disableSound)

然后在你的活动的 onCreate 上:

getIntent().getBooleanExtra("disableSound", false)

请注意最后一个参数 false 只是一个默认值。如果这是您想要的行为,您可以将其设置为 true。

【讨论】:

  • 如果您提到的方法破坏了活动,名称-值对是否仍然存在?
  • 我不确定我是否完全理解这个问题。事情是您在意图中放置的值在活动被销毁并启动新活动时由意图保留。这意味着一旦新活动开始,它仍然可用
  • 我明白你的意思,我们将这些值放在我们用来启动新活动的意图中。并且这个值在当前(旧活动)被销毁时保留在为其创建意图的新活动中。
  • 是的,该值保留在意图中。这就是为什么您需要调用 getIntent().getBooleanExtra,这将检索您用于启动新活动的意图。
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多