Problems understanding the life cycle when screen goes off and on

a 夏天 提交于 2019-11-28 20:28:40

See Activity Lifecycle documentation for a good description of the lifecycle, with diagrams.

Most likely your activity is killed with the screen goes off to save resources (battery power). As the documentation states, you can basically be killed anytime that Android wants to free resources. So, you should always design your activities to be able to be stopped and restarted at any time.

I had the same issue with my own game. My game works in landscape only, and when turning off the screen, the android screensaver takes the control (in portrait mode), thus sending an orientationChange that destroys and recreates the activity.

A simple solution is to declare that you will manage yourself screen orientation changes:

<activity ... android:configChanges="orientation" ... >

This is quite easy if your activity is declared to be landscape only (you have to do nothing), but can get harder if your activity can rotate...

Alexander Abakumov

Ruben's answer is completely correct, but only if your application targets the API level 12 or lower.

But since the API level 13 in addition to the orientation option, you have to declare the screenSize option, because it also gets triggered when a device switches between the portrait and the landscape orientations:

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

Otherwise, your activity would still be recreated an additional time when screen goes off on the API 13 or a higher platform.

For reference, see API docs, android:configChanges section notes.

Thats the way. If you read the activity life cycle you will see that the steps are pretty much ordered that way. Its not just when your screen goes on and off but also when you chnage the oreintation of the phone. Android recreated the activity following exactly the steps you have mentioned above. Try rotating you screen, you will see then! =)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!