Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity OnCreate called when phone goes to sleep

Tags:

android

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?

like image 316
iterator Avatar asked Nov 10 '10 20:11

iterator


People also ask

What is it called when an application is onCreate?

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

Which callback is called when the activity is no longer visible in Android?

When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback. This may occur, for example, when a newly launched activity covers the entire screen.

Which method is called before activity is destroyed in Android?

The onDestroy() method runs immediately before the activity is destroyed. The onDestroy() method enables you to perform any final cleanup such as freeing up resources.

Why is onResume called after onCreate?

onResume() will never be called before onCreate() . Show activity on this post. onResume() will always be called when the activity goes into foreground, but it will never be executed before onCreate() .


2 Answers

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.

like image 82
ProjectJourneyman Avatar answered Sep 20 '22 13:09

ProjectJourneyman


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 !

like image 38
Netero Avatar answered Sep 17 '22 13:09

Netero