This behavior is built into the activity and fragment lifecycle as instance states:
You can save the instance state using Activity.onSaveInstanceState(Bundle savedInstanceState)
where you add items into a Bundle.
Similarly, you can read this instance state in Activity.onCreate(Bundle savedInstanceState)
and Activity.onRestoreInstanceState(Bundle savedInstanceState)
.
I strongly encourage you to read the documentation here.