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)).
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].
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.
I created a sample repository with short documentation how to reproduce my problem here: https://github.com/einvalentin/react-native-state-test
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.
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.
Thanks a lot!
The trick to keep on running something forever, like the timer you've seen above, is to make Service foreground, then it should show a notification that's it's performing some kind of background job, but Android indeed respects such Services and rarely kills them.
Go to Settings > Apps > App launch, locate the app that you want to keep running in the background and disable Manage automatically, then enable Run in background in the pop-up box of Manage manually. Then, enable Run in background and tap OK.
Instead, React Native uses Headless JS to execute JavaScript code in the background. In this article, we'll learn to execute background operations in React Native using Native APIs and Headless JS. Headless JS is available only for Android, therefore, we'll focus only on Android development in this article.
If you are using Redux for state management you should probably use redux-persist. If not you have a couple of different options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With