Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I persist state for android apps killed in the background in react-native

Tags:

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!

like image 575
Valentin Avatar asked Feb 20 '17 17:02

Valentin


People also ask

How do I keep apps running in background React Native?

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.

How do I keep any app permanently alive in the background in Android?

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.

Is it possible to run a React Native app in the background?

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.


1 Answers

If you are using Redux for state management you should probably use redux-persist. If not you have a couple of different options:

  • AsyncStorage
  • Realm React Native
like image 165
wmcbain Avatar answered Oct 02 '22 03:10

wmcbain