3

我将状态数据保存在活动的 onSaveInstanceState 函数中,然后在 onRestoreInstanceState 中恢复该数据。这段代码在 95% 的情况下都能正常工作。

我发现了一个测试用例,导致 Android 从测试到测试产生不同的结果,我不知道为什么。我有最初的 Droid 手机,它有一个滑出式键盘。在我的应用程序中,我执行了 2 个测试用例,这些用例允许我重现由于未调用 onRestoreInstanceState 而未恢复数据的情况。测试几乎相同,但由于我收到的结果略有不同,显然有些不同。

测试用例 1(纵向模式下的电话,键盘输入):

1. Populate the Activity with data
2. Press my phone's power button to purposely dim the screen. (The phone is now locked)
3. Immediately after step 2, slide out my phone's keyboard, switching the phone to landscape mode.
4. About 80% of the time, the screen lights up, giving me the option to unlock the phone. (See difference in other test case).
5. Unlock the phone, which immediately takes me to my last Activity. Function onRestoreInstanceState is not called about 75% of the time.

测试用例 2(手机处于横向模式,键盘不在):

1. Populate the Activity with data
2. Press my phone's power button to purposely dim the screen. (The phone is now locked)
3. Immediately after step 2, slide in my phone's keyboard, switching the phone to portrait mode.
4. Majority of the time, the screen is not lit up. I have to press my phone's power button to light the screen up, which then allows me to unlock the phone.
5. Unlock the phone, which immediately takes me to my last Activity. Function onRestoreInstanceState is not called about 20% of the time.

测试用例 1 大约 60% 的时间不会恢复数据。测试用例 2 大约 20% 的时间无法恢复数据。对我来说真正突出的唯一区别是在推入或滑出键盘后屏幕被点亮。当那个屏幕亮起时,数据几乎每次都消失了。

如果我调暗屏幕,然后在解锁手机并返回应用程序之前连续滑动键盘大约 10 次,我几乎100% 的时间都会重现这个问题。

在所有成功恢复数据的情况下,调用顺序如下:

onSave
onStop
onDestroy
onCreate
onStart
**onRestore**
onResume

在所有未能成功恢复数据的情况下,调用顺序为:

onSave
onStop
onDestroy
onCreate
onStart
onResume

有人能告诉我这里发生了什么吗?为什么我得到不同的结果,执行相同的精确测试?如果我一遍又一遍地运行测试用例#1(或#2),结果永远不会相同。我想了解为什么会发生这种情况,但更重要的是(如果无法给出明确的答案),我只想每次都保存数据,那我该怎么办?我认为将 onRestoreInstanceState 中的代码移动到 onCreate 可以解决问题,但我只是运行了几次测试用例,发现有时传递给 onCreate 的 Bundle 为空,这意味着我的数据没有得到恢复。

如果我不能指望 onCreate 中的 Bundle,也不能指望 onRestoreInstanceState 被调用,那还剩下什么?我唯一的选择是 onResume 吗?这个活动维护了很多数据。我是否应该考虑使用 onRetainNonConfigurationInstance 和 getLastNonConfigurationInstance,在 onResume 中调用 getLastNonConfigurationInstance?以前我使用过这些功能,但由于数据丢失而放弃了它们。我当时不知道为什么,但我怀疑是因为这个确切的问题。但是当我之前使用它们时,我在 onCreate 中调用了 getLastNonConfigurationInstance。如果从 onResume 调用它可能会有所不同/更好?

4

0 回答 0