我如何为在 react-native 中在后台杀死的 android 应用程序保持状态 [英] How do I persist state for android apps killed in the background in react-native
问题描述
当一个 Android 应用程序被发送到后台时,它可以保持其实例状态,以防它因内存不足而被杀死(参见 Activity:onSaveInstanceState() 和 Activity:onCreate(Bundle savedInstanceState)).
When an Android App is sent to the background, it can persist its instance state in case it gets killed due to low memory (see Activity:onSaveInstanceState() and the bundle argument for Activity:onCreate(Bundle savedInstanceState)).
默认的 Activity 行为是保存视图层次结构的状态,因此在很多情况下,您无需编写任何代码,它就可以工作"[tm].
The default Activity behaviour is saving the state of the view hierarchy so for a lot of cases you don't have to write any code and it "just works"[tm].
现在对于 react-native 这不是真的.React 本机应用程序托管在单个 MainActivity 中,它们的状态包含在应用程序的 javascript 解释器中.
Now for react-native this is not true. React native apps are hosted in a single MainActivity and their state is contained in the javascript interpreter in the app.
我创建了一个示例存储库,其中包含如何在此处重现我的问题的简短文档:https://github.com/einvalentin/react-native-state-test
I created a sample repository with short documentation how to reproduce my problem here: https://github.com/einvalentin/react-native-state-test
我希望 react-native 挂钩到原生 android 应用程序状态序列化机制,同时为应用程序开发人员提供挂钩以在他们需要自定义序列化时进行扩展.或者,我可以看到自己扩展 MainActivity 以将生命周期事件转发到 Javascript 层并在那里手动执行一些自定义状态序列化 - 但这感觉有点笨拙.
I would want react-native to hook into the native android app state serialisation mechanism while providing application developers hooks to extend if they need custom serialisation. Alternatively I could see myself extending the MainActivity to forward the lifecycle events to the Javascript layer and do some custom state serialisation manually there - but this feels a bit clunky.
是否有一种明显的方法被我忽略了在 react-native 中保存状态,以便在后台被杀死的应用程序不会从头开始?例如,在与您的应用交互时接听电话的低内存设备上总是会发生这种情况.
Is there an obvious way I have overlooked to save the state in react-native so that apps that are killed in the background are not restarted from scratch? This can always happen for example on low memory devices receiving a phone call while interacting with your app.
非常感谢!
推荐答案
如果您使用 Redux 进行状态管理,您可能应该使用 redux-persist.如果没有,您有几个不同的选择:
If you are using Redux for state management you should probably use redux-persist. If not you have a couple of different options:
这篇关于我如何为在 react-native 中在后台杀死的 android 应用程序保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!