android生命周期

原创
2014/04/18 13:48
阅读数 111

笔记来源 http://developer.android.com/training/basics/activity-lifecycle/starting.html

1. Starting an Activity

Unlike other programming paradigms in which apps are launched with a main() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its lifecycle. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.

于其他编程规范使用main()方法启动不同的是, Android系统启动代码在一个活动实例通过调用特定的回调方法来对应特定的生命周期的阶段。通过一系列回调方法来启动一个Activity,同时通过一系列回调方法来销毁一个Activity。

 

 

 

 

2. Destroy the Activity


While the activity's first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory. 

onDestory作为一个信号由系统调用,这个信号的意思是当需要被彻底的把这个activity从系统内存中移除的时候。

 

Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during onPause() and onStop(). However, if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().

     大部分的应用都可以不关心 onDestroy)()这个方法,而需要在onPause(), onStop() 两个方法中做清理处理。 当然,如果在onCreate() 方法中启动了一个长时间运行且消耗资源的后台进程,并且如果不关闭可能导致内存溢出,你就应该在onDestory()中把它干掉。

@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass
   
    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}

Note: The system calls onDestroy() after it has already called onPause() and onStop() in all situations except one: when you call finish() from within the onCreate() method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call finish() from withinonCreate() to destroy the activity. In this case, the system immediately calls onDestroy() without calling any of the other lifecycle methods.

提示:大部分情况下,调用onDestory()都会在 系统会在调用 onPause()和onStop()之后,有一个例外:当你在onCreate()方法中立即调用finish()方法。 比如说你的activity只是作为一个启动其它activity的临时决定层,你就有可能在onCreate()方法中调用 finish() 来销毁这个临时的activity。 这种情况下,系统不会调用其它生命周期的回调方法,而是立刻调用 onDesotry()方法来干掉当前activity。

 

 

 

 

笔记来源:http://developer.android.com/training/basics/activity-lifecycle/recreating.html

3. Recreating an Activity

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses theBack button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

正常销毁(destroy)Activity的场景:点击返回按钮,调用 finish() 方法。

系统销毁: 前台需要系统资源而你的activity长期间不活动。

 

When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of thatActivity instance is gone forever because the behavior indicates the activity is no longer needed. However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

activity销毁意味着啥子都没得了。 你要它自己销毁还好,没得就没得了,如果是系统干得,就可能丢失之前输入过的数据或者流程。但是系统会自动保存一些销毁它之前的数据,下次回来的时候可以直接重现之前的场景。

Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

注意: 在屏幕旋转的时候也需要销毁activity。原因:略。

By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.

Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.

Figure 2. As the system begins to stop your activity, it calls onSaveInstanceState() (1) so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined at (1) to both the onCreate() method (2) and theonRestoreInstanceState() method (3).

Save Your Activity State


As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-value pairs. The default implementation of this method saves information about the state of the activity's view hierarchy, such as the text in an EditText widget or the scroll position of aListView.

To save additional state information for your activity, you must implement onSaveInstanceState() and add key-value pairs to the Bundle object. For example:

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public 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);
}

Caution: Always call the superclass implementation of onSaveInstanceState() so the default implementation can save the state of the view hierarchy.

Restore Your Activity State


When your activity is recreated after it was previously destroyed, you can recover your saved state from theBundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

For example, here's how you can restore some state data in onCreate():

@Override
protected 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
    }
    ...
}
 
在Oncreate里面传入的savedInstanceState 有可能为null,所以在这个获取保存的状态的话需要先判空。 建议实现 onRestoreInstanceState() 方法而不是在onCreate()方法中恢复原来的数据。因为只有savedInstanceState不为空的情况下,onRestoreInstanceState()才会被调用。

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:

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);
}

Caution: Always call the superclass implementation of onRestoreInstanceState() so the default implementation can restore the state of the view hierarchy.

To learn more about recreating your activity due to a restart event at runtime (such as when the screen rotates), read Handling Runtime Changes.

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部