Android学习笔记(Google官方教程)(三)

来源:互联网 发布:wear it on 编辑:程序博客网 时间:2024/05/16 00:41

管理Activity的生命周期

启动Activity

生命周期

状态

  • Resumed:这个状态下,activity运行在前台,并且能够与用户进行交互
  • Paused:这个状态下,该activity被另一activity遮盖部分,也就是说,另一activity运行在前台且是半透明状态,或者并未填充整个屏幕。暂停的activity不会收到任何用户输入,并且不能执行任何代码
  • Stopped:这个状态下,activity运行在后台,完全隐藏或者不对用户可见。在这个状态下,这个activity的实例和它的状态信息(成员变量)将会被保持,但是不能执行任何代码。

调用方法

  • onCreate:activity创建的时候被调用
  • onStart:onCreate或onRestart调用的时候调用
  • onResume:onStart方法调用的时候调用,可用来开启动动画,打开设备
  • onPause:activity运行在后台的时候调用,但是还没有被杀死
  • onStop:activity不再可见的时候调用
  • onDestory:activity被摧毁的时候调用

指定进入的Activity

<activity android:name=".MainActivity" android:label="@string/app_name"><intent-filter>    <action android:name="android.intent.action.MAIN" />    <category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

Activity的暂停和恢复

暂停状态

  • 停止动画或者其他可能消耗CPU的动作
  • 提交未保存的修改
  • 释放系统资源

恢复状态

  • 开始动画
  • 初始化资源

Activty的停止和重启

重启状态

  • 在主页重新进入或者从最近的Apps窗口进入
  • 按下返回键的时候
  • 使用app收到电话的时候

停止状态

  • 进行耗时的CPU操作,比如写入数据库

重新创建Activity

  • 使用Bundle来保存状态
  • 需要重写onSaveInstanceState()回调方法
  • 系统重新创建时,会将Bundle传递给onRestoreInstanceState() 和onCreate() 方法。

保存Activity的状态

  • 调用 onSaveInstanceState()
  • static final String STATE_SCORE = "playerScore";static final String STATE_LEVEL = "playerLevel";...@Overridepublic void onSaveInstanceState(Bundle savedInstanceState) {// Save the user's current game state    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);// Always call the superclass so it can save the view hierarchy state    super.onSaveInstanceState(savedInstanceState);}

恢复Activity的状态

  • 调用 onCreate() 或 onRestoreInstanceState()
  • @Overrideprotected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState); // Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) {       // Restore value of members from saved state       mCurrentScore = savedInstanceState.getInt(STATE_SCORE);       mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);   } else {      // Probably initialize members with default values for a newinstance  }  ...}
  • onRestoreInstanceState() 系统将在onStart()调用后调用该方法
  • public void onRestoreInstanceState(Bundle savedInstanceState) {    // Always call the superclass so it can restore the view hierarchy    super.onRestoreInstanceState(savedInstanceState);    // Restore state members from saved instance    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);}
0 0
原创粉丝点击