android学习笔记2:Activity的生命周期

Activity的状态转换图

按照我的理解,Activity启动调用onCreate方法,然后状态是Created;随即执行onStart方法,状态是Started,此时界面可见;迅即执行onResume方法,状态保持在Resumed,界面处在屏幕最前;若此时弹出对话框之类的,导致不在最前不接受用户输入但依然露出部分界面,则调用onPause方法,状态为Paused;对话框关闭后调用onResume回到Resumed状态;如果看不见界面则执行onStop,状态为Stopped;切换回界面则执行onRestart和onStart,回到Started状态向Resumed发展。如果关闭Activity则调用onDestroy方法。

如果在 onCreate() 启动了线程或者占用了资源,应在onDestroy()结束线程释放资源,以免导致内存溢出。

Paused状态之后可能返回Resumed状态,但通常是进入Stopeed的前奏,因此在onPause中应做如下事情:

  • 停止正在进行的消耗 CPU的操作.
  • 保存改变 (如email草稿).
  • 释放系统资源, 例如 broadcast receivers, handles to sensors (like GPS), 或其它用户不在使用但依然运行会消耗电量的资源.
  • Stop animations or other ongoing actions that could consume CPU.
  • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
  • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.例如释放掉占用的摄像头:
    @Override
    public 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;
        }
    }
    当回到Activity时,应在onResume重新获取在onPause释放的资源(二者刚好是相对应的,正如onCreate对于onDestroy)。

    在onStop应做一些保存数据到数据库之类比较占用资源的操作(不要放在onPause)。

    在onStart应判断需要的资源是否可用(如GPS)。

  • Stop animations or other ongoing actions that could consume CPU.
  • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
  • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值