简体   繁体   中英

Android activity restarting

I have developed an Android app which is working fine but while the app works if I plug the device into a car charger and start the vehicle the activity gets auto restarted and all the values in the current activity get lost. Is someone experienced in this and has any solution? Can DC current effect the device or activity?

Android is restarting your activity because of the configuration change. Try to use ViewModel to save activity state when the activity destroyed.

There are many reasons your activity can get destroyed, recreated/restarted, so you only need to prepare your app for any scenario that may come up, such that the activity instance state can be saved.

You can use any of the following depending on your scenario or preference:

  1. Save data in a Bundle in the OnSaveInstanceState callback method.

  2. ViewModel (with LiveData).

  3. Shared Preferences

Any app open on your device will restart when you plugged usb on your device.

When you're using fragment try to use onSaveInstanceState, try this link ( Once for all, how to correctly save instance state of Fragments in back stack? )

When you're using activity try to use variable to store values of the views.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM