简体   繁体   中英

When is an activity forcefully recreated?

The Android docs say that configuration changes can force an activity to be recreated, the most common change being a rotation. Now, there are some methods that can determine whether an activity is being destroyed to be recreated but all(?) of these methods are called after onStop() and aren't guaranteed or recommended for data saving purposes.

To give an example, there is an EditText activity which autosaves what they have written/updated if the user navigates away from the app via back button, app switch, etc However, the user might not want to save their changes when there is a configuration change so I need to be prepared for those cases.

When an activity is destroyed by the system because of configuration change onSaveInstanceState is called.

 @Override
 protected void onSaveInstanceState(Bundle outState) {            
    super.onSaveInstanceState(outState);
 }

Store data that you want to persist in outState bundle.

Then you'll receive the stored data in onCreate and onRestoreInstanceState.

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
}

Use it to retrieve data you had stored in onSaveInstanceState earlier.

By default System saves the state of few widgets (EditText , TextView) on it's own and this magic happens in super.onSaveInstanceState() .

@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); }

So if you do not want to save the text in EditText , just do editText.setText("") before calling super.onSaveInstanceState() .

Hope this helps.

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