您的位置:首页 > 移动开发 > Android开发

Android开发——Activity生命周期中的一些注意点

2015-08-30 16:53 561 查看


1. Activity的onDestory()在Activity关闭时一定会被调用吗?

There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.


上面是官网的话,意思大概是,有很多情况下系统会简单的杀死这个Activity的宿主进程而不调用它的onDestroy方法,所以在这个方法中不要做任何有关保留数据或者状态的相关操作。

从官网生命周期图我们可以看到Activity有两个出口,onStop后有可能直接到 App process killed,而不执行onDestroy函数。

2. 按下home键后 Activity发生什么变化?

onPause –> onSaveInstanceState –> onStop


程序在后台的时候,选择主动杀死程序进程,然后再从桌面点击应用启动

onStart –>onRestoreInstanceState - > onResume
" data-snippet-id="ext.985723908b317cdb0e47782db9856314" data-snippet-saved="false" data-csrftoken="zE7kqcfS-rPA0pfTUkywJOuJi__ohA2zmfR0" data-codota-status="done">[code]    onCreate ->onStart –>onRestoreInstanceState - > onResume


直接从桌面点击应用启动呢?

onRestart –> onStart –> onResume


按下返回按键

onPause –> onStop –> onDestroy


onSaveInstanceState()和onRestoreInstanceState 方法是什么呢?

3. onSaveInstanceState() 和 onRestoreInstanceState()

来自胡凯

onSaveInstanceState与onRestoreInstanceState的作用:

在资源紧张的情况下,系统会选择杀死一些处于非栈顶的Activity来回收资源。 为了能够让这些可能被杀死的Activity能够在恢复显示的时候状态不丢失,所以需要在Activity从栈顶往下压的时候提供onSaveInstanceState的回调用来提前保存状态信息。

而onRestoreInstanceState则是在这个Activity真的回收掉之后的恢复显示阶段用来恢复之前保存的数据。

onSaveInstanceState与onRestoreInstanceState的调用时机:

只要某个Activity是做入栈并且非栈顶时(启动跳转其他Activity或者点击Home按钮),此Activity是需要调用onSaveInstanceState的, 如果Activity是做出栈的动作(点击back或者执行finish),是不会调用onSaveInstanceState的。

只有在Activity真的被系统非正常杀死过,恢复显示Activity的时候,就会调用onRestoreInstanceState。

4. 屏幕旋转时,Activity执行了什么方法?

如果你不做任何配置

启动Activity会执行如下方法:

onCreate –> onStart –> onResume


之后旋转屏幕,则Activity会被销毁并重新创建,之后便会执行如下方法:

onSaveInstanceState –> onStop –> onDestroy –> onCreate –> onStart –> onRestoreInstanceState –> onResume
" data-snippet-id="ext.853875dd1810fa8e66a574b85f570628" data-snippet-saved="false" data-csrftoken="sLRS6Y1X-wXBfz4nAaIhM3QIxZeMeFW-y-AI" data-codota-status="done">[code]onPause –> onSaveInstanceState –> onStop –> onDestroy –> onCreate –> onStart –> onRestoreInstanceState –> onResume


5. 屏幕旋转不重建Activity

在AndroidManifest配置文件里声明android:configChanges属性

13时需加上screenSize)" data-snippet-id="ext.7c24116942ba8a2c3d69a054d026c5ad" data-snippet-saved="false" data-csrftoken="aeVpge75-TL-szOrrtsoVWRMItyXjf5ZvJAI" data-codota-status="done">[code]android:configChanges="keyboardHidden|orientation|screenSize"(sdk>13时需加上screenSize)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: