Android-持久化活动实例
我正在应用程序中使用两个活动(A和B)的实例。现在我面临着坚持每一个的问题。当我使用SharedReferences时,我只能使用SharedReferences持久化A.class和B.class,但是当我再次使用实例A时。它在SharedReferences中的持久状态被覆盖。我想,我应该在SavedInstanceState和RestoredInstanceState上使用Bundle。但是如何将保存的Bundle传递到onCreate()?目标是能够持久化活动实例Android-持久化活动实例,android,android-activity,persistence,instance,Android,Android Activity,Persistence,Instance,我正在应用程序中使用两个活动(A和B)的实例。现在我面临着坚持每一个的问题。当我使用SharedReferences时,我只能使用SharedReferences持久化A.class和B.class,但是当我再次使用实例A时。它在SharedReferences中的持久状态被覆盖。我想,我应该在SavedInstanceState和RestoredInstanceState上使用Bundle。但是如何将保存的Bundle传递到onCreate()?目标是能够持久化活动实例 感谢启动活动A时使用i
感谢启动活动A时使用
intent.putExtra(字符串名称,捆绑包值)
将捆绑包传递给活动,然后在活动A的onCreate中使用getIntent.getBundleExtra(字符串名称)
再次获取捆绑包你需要考虑你需要坚持什么样的状态。
比如,
- 勾选了哪些复选框
- 用户处于什么级别
- 光标的位置是什么
- 他们正在查看哪一级别的抽认卡(可能是第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状态当您切换到某个活动时,Android将调用该活动上的
onRestoreInstanceState
方法。此时您应该恢复状态。由android决定是创建新实例,还是切换到以前的现有实例。您不应该尝试手动持久化实例。你只需要告诉android如何保存和加载你关心的状态。好吧,但这会产生一个问题——如何存储捆绑包?在方法onSaveInstanceState中,假设我将其保存为某个文件,或者像字符串一样保存到SharedReferences中。应用程序被系统强制关闭,现在我需要恢复实例。为此,有一个方法onRestoreInstanceEstate,但它需要Bundle作为参数。此捆绑包不存在,必须先加载。但是在哪里加载它呢?如果你看我的例子,有两个部分onSaveInstanceState
和onRestoreInstanceState
。它们协同工作以确保正确保存和恢复捆绑包。试试看。好吧,所以不管活动A的实例数有多少,在恢复时每个实例都会有不同的捆绑包?问题是活动A是一个启动意图,我不知道如何存储捆绑包。我正在使用一个活动的多个实例,每个实例都必须持久化