【问题标题】:Android - persisting activity instanceAndroid - 持久化活动实例
【发布时间】:2011-10-14 09:43:22
【问题描述】:

我在我的应用程序中使用了两个活动(A 和 B)的实例。现在我面临着坚持每个人的问题。当我使用 sharedpreferences 时,我只能使用 SharedPreferences 持久化 A.class 和 B.class,但是当我再次使用实例 A 时。它在 SharedPreferences 中的持久状态被覆盖。我认为,我应该使用带有 onSavedInstanceState 和 onRestoredInstanceState 的 Bundle。但是如何将保存的 Bundle 传递给 onCreate() 呢?目标是能够持久化活动实例。

谢谢

【问题讨论】:

标签: android android-activity persistence instance


【解决方案1】:

在启动活动 A 时。您可以使用 intent.putExtra( String name, Bundle value ) 将包传递给您的活动,然后在活动 A 的 onCreate 中使用 getIntent.getBundleExtra( String name ) 再次获取您的包。

【讨论】:

  • 问题是activity A是一个起始意图,我不知道如何存储Bundle。我正在使用一个活动的多个实例,每个实例都必须持久化
【解决方案2】:

你需要考虑你需要坚持什么状态。

例如;

  • 勾选了哪些复选框?
  • 用户处于什么级别?
  • 光标的位置是什么

例如, 我刚刚完成了一个应用程序,用户可以在其中查看不同级别的抽认卡。

我在乎;

  • 他们正在查看哪个级别的抽认卡(可能是第 2 级)
  • 他们在看哪张卡片(可能在第四张卡片上)

这是代码。

// a variable to store the level
private final static String CARD_LEVEL_STATE = "currentCardLevel";

// a variable to store the current card
private final static String CURRENT_CARD_STATE = "currentCardNumber";

@Override
protected void onSaveInstanceState(Bundle outState) {
  // save the level
  outState.putInt(CARD_LEVEL_STATE,   flashCardList.currentLevel());
  // save the current card
  outState.putInt(CURRENT_CARD_STATE, flashCardList.currentCardNumber());
  // do the default stuff
  super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
  // ignore if we have no saved state
  if (savedInstanceState != null) {
    // record the level
    if (savedInstanceState.containsKey(CARD_LEVEL_STATE)) {
      int currentCardLevel = savedInstanceState.getInt(CARD_LEVEL_STATE);
      flashCardList.setCardLevel(currentCardLevel);
    }
    // recover the current card
    if (savedInstanceState.containsKey(CURRENT_CARD_STATE)) {
      int currentCardNumber = savedInstanceState.getInt(CURRENT_CARD_STATE);
      flashCardList.setCurrentCardNumber(currentCardNumber);
    }
    // refresh the view
    refreshCard();
  }
  super.onRestoreInstanceState(savedInstanceState);
};

【讨论】:

  • 那么结果如何呢?尽管我正在使用我的活动的多个实例,但我是否只能拥有 onSaveInstanceState 和 onRestoreInstanceState 事件?我想保持数据结束 GUI 状态
  • 当你切换到一个activity时,Android会在activity上调用onRestoreInstanceState方法。这是您应该恢复状态的时候。它是创建一个新实例,还是切换到以前的现有实例,这取决于 android。您不应尝试手动持久化实例。你只需要告诉android如何保存和加载你关心的状态。
  • 好的,但是这个问题出现了——如何存储Bundle?在方法 onSaveInstanceState 中,假设我将它作为文件保存在某处,或者像字符串一样保存到 SharedPreferences 中。应用程序被系统强制关闭,现在我需要恢复实例。为此,有一个方法 onRestoreInstaneceState,但它需要 Bundle 作为参数。这个包在这里不存在,它必须先加载。但是在哪里加载呢?
  • 如果你看我的例子,有两个部分 onSaveInstanceStateonRestoreInstanceState。他们一起工作以确保正确保存和恢复捆绑包。试试看吧。
  • OK,所以不管activity A的实例数量,每个恢复的时候会有不同的Bundle?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多