Android Training - 管理Activity生命週期

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(), 就會直接跳轉到onDestroy();


<application ... >
    ...
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>
The android:parentActivityName attribute declares the name of this activity's parent activity within the app's logical hierarchy. The system uses this value to implement default navigation behaviors, such as Up navigationon Android 4.1 (API level 16) and higher. You can provide the same navigation behaviors for older versions of Android by using the Support Library and adding the <meta-data> element as shown here.

爲Activity指明parentActivityName 主要是用於ActionBar的home按鈕導航用;對低版本的系統可以使用 <meta-data> 和support library來支持;


When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.


系統在特殊情況下(例如內存緊張)可能會直接kill在後臺的Activity,而不調用onDestroy(), 因此必須保證在onStop()中處理會導致memory leak的資源;


Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

onPause執行時間過長會影響到新的ACT出現的時間,因此一些比較耗時的操作應放到onStop裏面來做,例如操作SQLite;


When your activity comes back to the foreground from the stopped state, it receives a call to onRestart(). The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time). The onRestart() method, however, is called only when the activity resumes from the stopped state, so you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.


onRestart方法只有在Act從Stoped回到Resumed的時候纔會調用,can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.  


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.

When your activity is destroyed because the user presses Backor 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.

Act在以下幾種情況會調用onDestroy:

1. Back鍵導航

2. 在程序中調用了finish()

3. 因長時間處於Background而被系統kill掉,在這種情況下系統會保存一個bundle來記錄Act被銷燬時的狀態;


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).


每次屏幕方向變換的時候Act會被destroy and recreate; 如果不想這樣,在manifest裏面聲明

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

向系統表明Act會自己處理這類變化而不需要destroy和recreate, 此時可以重寫onConfigurationChanged來處理系統狀態變化;


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.

系統會默認在bundle中存儲每個view的狀態(例如edittext中的文本)並自動幫你restore,但如果你還想將一些member var 記錄下來,需要處理onSaveInstanceState(),在其中記錄並在 onRestoreInstanceState()onCreate() 從bundle中取回這些值;


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.




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:


onRestoreInstanceState()在onStart後調用,而且只有在當前有Saved bundle可用時纔會調用;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章