Activity的生命周期管理

来源:互联网 发布:矩阵变换 编辑:程序博客网 时间:2024/04/30 15:33

关于Activity的生命周期管理,官方文档有很详细的介绍:http://developer.android.com/training/basics/activity-lifecycle/index.html,下面只说下需要注意的地方。

1,首先来看一下Activity的生命周期回调


上图是Activity的生命周期的一个简单描述,我们根据项目需求来重写需要实现的回调方法。了解每一个回调方法的使用情况才能让我们的app表现更好,例如:

  • Does not crash if the user receives a phone call or switches to another app while using your app.
  • Does not consume valuable system resources when the user is not actively using it.
  • Does not lose the user's progress if they leave your app and return to it at a later time.
  • Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.
2,在Activity的生命周期中,可以从一个状态过渡到另一个状态,但是,Activity只能静止停留在以下三种状态中的一种:

Resumed
In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the "running" state.)
Paused
In this state, the activity is partially obscured by another activity—the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.
Stopped

In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.

3,onResume()和onPause()

onPause()和onResume()经常配套使用,当执行onPause()方法,意味着activity还部分可见,但是很多情况下是用户准备离开这个activity,并且随之将调用onStop(),所以在onPause()方法中我们应该做以下事情:

  • 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.
例如:你的应用使用了Camera功能,在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的操作,例如数据库操作,因为这样会减慢可见过渡到下一个activity的过程,应该放在onStop()方法中。

当activity回到前台可见的时候,onResume()方法就会调用,我们可以在该方法中初始化在onPause()方法中释放的组件,例如刚才的Camera:

@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    }}
4,onStop()

在onStop()方法中,我们应该释放掉绝大多数不再需要的资源,因为onStop()执行后,系统可能由于回收内存而直接干掉activity,极端情况下可能直接干掉进程而不执行onDestroy()方法,因此在onStop()方法中来释放资源避免内存泄露。

5,保存信息

有时候,由于不正常的行为导致activity销毁并重新创建,例如屏幕旋转,这样原先的一些状态信息就会丢失,例如之前用户输入的信息,用户当然不想再重新输入一遍,为了保留这些信息,可以在onSaveInstanceState()方法中使用Bundle来保存数据,然后在onRestoreInstanceState()方法和onCreate()方法中重新获取这些数据。

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);}
@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 new instance    }    ...}
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
原创粉丝点击