Activity生命周期管理之二——Pausing或者Resuming一个Activity
app使用期间,前台Activity经常被其他的可视组件遮挡,进入paused状态,例如一个对话框弹出时,只要Activity部分可见,但没获得焦点,就处在paused状态
然而,一旦Activity完全不可见,就处在stopped状态
当Activity进入paused状态时,系统调用onPause()方法,其中你可以停止一些任务,或者保存一些数据防止用户其后又退出,如果用户又返回,可以调用onResume()方法脱离paused状态
Pause你的Activity
当Activity接到一个onPause()调用,技术上意味着Activity部分可见,但通常表示用户离开这个Activity,即将进入stopped状态,在onPause()中,通常要做一下事情:
停止动画或者其他正在进行的耗费CPU的动作提交未保存的变化,但是只有在用户认为数据应该被保存的时候,例如邮件的草稿释放系统资源,例如broadcast receivers, 传感器句柄(例如GPS),或者其他影响电池电量而用户有不用的资源例如,使用照相机,在onPause()中就可以关掉
@Overridepublic void onPause() { super.onPause(); // Always call the superclass method first // Release the Camera because we don't need it when paused // and other activities might need to use it. if (mCamera != null) { mCamera.release() mCamera = null; }}
通常,不应该在onPause()中关闭CPU敏感的资源,像database connection,会延缓Activity之间的转换,他们最好在onStop()中实现
如果Activity将要进入Stopped状态,在onPause()中就要相对简单的完成操作以使用户能尽快转到下一个Activity,免得影响用户体验
@Overridepublic void onResume() { super.onResume(); // Always call the superclass method first // Get the Camera instance as the activity achieves full user focus if (mCamera == null) { initializeCamera(); // Local method to handle camera init }}