简体   繁体   中英

onSaveInstanceState() not called on custom view when app is moved to background

In an app I am developing, I have a custom view in which I need to save the instance state when either the screen configuration changes or the app is moved to the background. I implement onSaveInstanceState() and onRestoreInstanceState(Parcelable savedInstanceState) and in the case of screen configuration changes, the instance state is saved and restored perfectly. However, when the app is moved to the background, onSaveInstanceState() is not called. This means I have no saved instance state when the activity is brought to the foreground again. My question is then:

Why is onSaveInstanceState() not called when the app is moved to the background, and is it possible to make my view call onSaveInstanceState() when the app is moved to the background?

It occurs when you press the back button to leave the activity. – Zero

When using the Back button to leave the application the onSaveInstanceState method is not called by the Android system, this is expected system behavior. The back button is meant to stop your app (Read: activity).

The Back button finishes your Activity and there is no need to save app state. But if there is reason to to this then you should override the onStop method for example and save data to the file system there.

Sources:

http://developer.android.com/training/basics/activity-lifecycle/recreating.html (Recomended read)

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish().

As per my knowledge, when app enter into background, on Activity it calls onPause() method. So please try by moving your code to onPause() method.

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