Folding/unfolding triggers a configuration change for smallestScreenSize, screenSize and screenLayout.
This configuration change is similar with apps that are configured in multi-window mode. Even apps that does not support multi-window can be resized when a device gets folded or unfolded.
Whenever a configuration change occurs, the default case is that the whole activity is destroyed and recreated.
It is important to restore the previous state when the activity is restarted. To properly save and restore the previous state you can use onSaveInstanceState() and ViewModel object.
You can save the state in onSaveInstancesState() before your activity is destroyed and restore in onCreate() or onRestoreInstanceState().
If you want handling configuration change without restart, you need to add an android:configChanges attribute to your manifest with at least these values below.
With this attribute, you will need to manually update your view layout and reload resources in onConfigurationChaged().
<activity android:name=".MyActivity" android:configChanges="screenSize|smallestScreenSize|screenLayout" />
Do not call finish() or kill the process by itself in the activity’s onDestroy(). This will cause the app to close when a device gets folded or unfolded.
Please refer to the detail in Android developer guide