In Android development, if some events are triggered (such as screen spin events), the Activity will re-call the onCreate method to re-initialize the Activity, which is not only inefficient, but also causes data loss, the solution is to override the onConfigurationChanged method, and in AndroidManifest. declare configChanges for the Activity IN xml, so that the onConfigurationChanged method is called when a specific event is triggered, rather than the onCreate Method for reinitialization.
Generally, the following code is added to specify Activity in AndroidManifest. xml:
android:configChanges="orientation|keyboard|keyboardHidden"
This Code indicates that the onConfigurationChanged method of Activity is called when the device rotates, displays the keyboard, and hides the keyboard. If this statement is not declared, the onCreate method is called when a specific event is triggered.
The following is a Demo. We use data to simulate data changes when testing the screen rotation.
public class MainActivity extends Activity {private static final String TAG = "TEST";private int data;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "onCreate");}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();data = (int) (Math.random() * 100);Log.i(TAG, "onStart : " + data);}@Overridepublic void onConfigurationChanged(Configuration newConfig) {// TODO Auto-generated method stubsuper.onConfigurationChanged(newConfig);Log.i(TAG, "onConfigurationChanged : " + data);}}
Three screen effects:
The data is retained because the onCreate method is not enabled for three screens.
In addition, note that: super. onConfigurationChanged (newConfig) in the onConfigurationChanged () method must not be omitted. Otherwise, an android. app. SuperNotCalledException exception will be thrown.