android – Activity OnCreate called when phone goes to sleep-ThrowExceptions

Exception or error:

When I press the sleep button on my Droid, my activity’s oncreate is getting called. Why is that happening? Why would the OS want to call OnCreate when the device is going to sleep? Is there any way to stop it, or at least know it’s because the phone was put to sleep?

How to solve:

This happens particularly for activities that are locked in rotation, e.g. have this in the manifest within the activity tags:

android:screenOrientation="portrait"

When you turn the screen off, it reads the accelerometer to determine the true orientation and changes to that before turning off.

So yes, the simple solution is adding configChanges as well, making it look something like this:

<activity 
    android:name=".MyActivity"
    android:screenOrientation="landscape"
    android:configChanges="orientation"
/>

You don’t need to indicate the screenOrientation, but if you don’t whatever orientation it is at when it starts is where it will stay unless you write code to handle the configuration changes.

As a side note, when I started testing my apps on ICS I had to handle a few quirks with a create/destroy/create cycle at the start of some activities. A few extra checks and balances are necessary to make the code universal.

###

I had the same Prob my app (game) reloaded whenever it come from sleep

here what i did to solve it

i add

<activity 
     android:configChanges="orientation|screenSize"
/>

hope this will help someone !

Leave a Reply

Your email address will not be published. Required fields are marked *