Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is onCreate() called upon rotation

Tags:

android

For Android versions later than 2.1, is onCreate() called upon rotation? I put a log print in onCreate(), but it does not print for 2.3.3 and 4.0.3.

Here's the code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Runtime runtime = Runtime.getRuntime();
    long free = runtime.freeMemory();
    long total = runtime.totalMemory();
    long occupied = total - free;

    Log.i("MEM", "heap: " + occupied);
}

On 2.1, the log message prints multiple times due to orientation; on 2.3.3, it only prints once.

like image 528
dacongy Avatar asked Mar 06 '26 08:03

dacongy


2 Answers

if you declared the android:configChanges="orientation" flag , the activity will not be destroyed and recreated (onCreate() will not be called) and the callback

onConfigurationChanged()

will be called.

like image 105
K_Anas Avatar answered Mar 07 '26 21:03

K_Anas


As pointed before, if you want to avoid your activity from being recreated on rotation, thus calling onCreate() again, you must declare in your manifest corresponding configChanges.

In this case you'll have to set in your configChanges the rotation flag.

android:configChanges="orientation"

But, starting from Android 3.0 and above you have to declare also the screenSize value.

From http://developer.android.com/guide/topics/resources/runtime-changes.html:

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

So, now your configChanges will look:

android:configChanges="orientation|screenSize"
like image 30
Iñigo Avatar answered Mar 07 '26 21:03

Iñigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!