onSaveInstanceState() 可以手动调用吗?

Can onSaveInstanceState() be called manually?

我正在尝试在单击后退按钮时保存和检索我的 ActivityonSaveInstanceState()。我读过默认情况下它不会保存,因为假设用户在单击后退时已完成 Activity。但是,在我的应用程序中,情况并非如此,我想从内部调用 onSaveInstanceState():

@Override
public void onBackPressed() {
    super.onBackPressed();
}

但是,它会在屏幕旋转时保存。我读过的这也是默认行为。

我花了几天时间试图破解这个,但我就是一无所获。

I'm trying to save and retrieve my activities savedInstanceState when clicking the back button. I have read that by default it is not saved because it is assumed that the user is done with the activity when clicking back.

一切正确。此外,在这种情况下 Android 假定用户不再需要该应用程序,因此它可以安全地终止应用程序进程。

Can saveInstanceSate be called manually?

当然可以。 method is protected。但根据您的要求,这没有意义。在您的情况下,即使您作为方法参数传递的 "manual" Bundle 将被系统保存,驻留在 RAM 中的数据将由于后按而立即随应用程序进程本身消失。

It is, however, saved on screen rotation.

也是正确的。在这种情况下,Android 假定该应用程序仍在使用中,因此它(部分)关心为您恢复其状态。

However, in my app, this is not the case and I would like to saveInstanceState from within onBackPressed().

我怀疑你是否应该与 OS 习语作斗争。 Android 为您提供恢复应用程序状态的替代选项(因此用户 "thought" he/she 恰好在应用程序离开时返回到您的应用程序), 例如SharedPreferences、数据库、内部存储等。我建议坚持 OS 习语。

我建议使用 SharedPreferences 来持久化这种性质和场景的数据。通过这种方式,savedInstanceState() 的工作是手动完成的。此数据在应用程序过早死亡、配置更改等情况下幸存下来。