How do I persist state for android apps killed in

2020-07-02 08:28发布

问题:

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!

回答1:

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