Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onCreate is called after locking the screen

When I lock the screen while my app is running "on top", the system calls almost immediately onCreate (screen is still black). What could be the reason for this destructive behaviour?

like image 807
user2224350 Avatar asked May 01 '13 14:05

user2224350


2 Answers

This happens if Activity is in Landscape mode and Lock screen is enabled by user.

There can be two reasons behind this:

  1. If any type of lock screen is enabled and Activity is in Landscape mode: If device has the Lock Screen in Portrait Mode, when the device is locked it automatically switches to portrait mode (Even if your activity was in Landscape Mode). And when the device is unlocked, your Activity becomes visible, but it is again transitioning from Portrait (When locked) to Landscape, so the Activity gets Destroyed and Recreated.

  2. This is how Android Operating System works, it decides when to destroy your view. When you're locking your phone, you app goes to a pause state (onPause) of the activity lifecycle. When an activity is in pause state and if it takes a lot of memory, System has the rights to kill your app (onStop then onDestroy). So when you unlock it, system calls (onCreate) to re-create your view.

Solution:

  1. You should carefully save and check state using onSaveInstanceState() OR
  2. Use android:configChanges="orientation|screenSize" for your Activity Tag in Manifest.
like image 72
AnujDeo Avatar answered Sep 22 '22 14:09

AnujDeo


For me I've

android:configChanges="orientation"

but this doesn't help because my activity was full screen and so I added

android:configChanges="keyboardHidden|orientation|screenSize"

in the activity tag

As mentioned in Handling the Configuration Change Yourself

If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.

like image 42
Inder Kumar Rathore Avatar answered Sep 21 '22 14:09

Inder Kumar Rathore