Activity的生命週期

Activity從建立到銷燬的過程中需要在不同的階段調用7個生命週期方法。這7個生命週期方法的定義如下:

  1. protected void onCreate(Bundle savedInstanceState)
  2. protected void onStart()
  3. protected void onResume()
  4. protected void onPause()
  5. protected void onStop()
  6. protected void onRestart()
  7. protected void onDestroy()

 

上面7個生命週期方法分別在4個階段按着一定的順序進行調用,這4個階段如下:

  • 開始Activity:在這個階段依次執行3個生命週期方法:onCreate、onStart和onResume。
  • Activity失去焦點:如果在Activity獲得焦點的情況下進入其他的Activity或應用程序,這時當前的Activity會失去焦點。在這一階段,會依次執行onPause和onStop方法。
  • Activity重新獲得焦點:如果Activity重新獲得焦點,會依次執行3個生命週期方法:onRestart、onStart和onResume。
  • 關閉Activity:當Activity被關閉時系統會依次執行3個生命週期方法:onPause、onStop和onDestroy。

 

如果在這4個階段執行生命週期方法的過程中不發生狀態的改變,那麼系統會按着上面的描述依次執行這4個階段中的生命週期方法,但如果在執行的過程中改變了狀態,系統會按着更復雜的方式調用生命週期方法。

在執行的過程中可以改變系統的執行軌跡的生命週期方法是onPauseonStop。如果在執行onPause方法的過程中Activity重新獲得了焦點,然後又失去了焦點。系統將不會再執行onStop方法,而是按着如下的順序執行相應的生命週期方法:

 

onPause -> onResume-> onPause

 

如果在執行onStop方法的過程中Activity重新獲得了焦點,然後又失去了焦點。系統將不會執行onDestroy方法,而是按着如下的順序執行相應的生命週期方法:

 

onStop -> onRestart -> onStart -> onResume -> onPause -> onStop

 

1詳細描述了這一過程。

圖1  Activity的生命週期

 

從圖1所示的Activity生命週期不難看出,在這個圖中包含了兩層循環,第一層循環是onPause-> onResume -> onPause,第二層循環是onStop -> onRestart -> onStart -> onResume -> onPause-> onStop。我們可以將這兩層循環看成是整合Activity生命週期中的子生命週期。第一層循環稱爲焦點生命週期,第二層循環稱爲可視生命週期。也就是說,第一層循環在Activity焦點的獲得與失去的過程中循環,在這一過程中,Activity始終是可見的。而第二層循環是在Activity可見與不可見的過程中循環,在這個過程中伴隨着Activity的焦點的獲得與失去。也就是說,Activity首先會被顯示,然後會獲得焦點,接着失去焦點,最後由於彈出其他的Activity,使當前的Activity變成不可見。因此,Activity有如下3種生命週期:

  • 整體生命週期:onCreate -> ... ... -> onDestroy。
  • 可視生命週期:onStop -> ... ... -> onPause。
  • 焦點生命週期:onPause -> onResume。

注意:在圖1所示的Activity生命週期裏可以看出,系統在終止應用程序進程時會調用onPauseonStoponDesktroy方法。而onPause方法排在了最前面,也就是說,Activity在失去焦點時就可能被終止進程,而onStoponDestroy方法可能沒有機會執行。因此,應該在onPause方法中保存當前Activity狀態,這樣才能保證在任何時候終止進程時都可以執行保存Activity狀態的代碼。

 

源文檔 <http://dev.10086.cn/cmdn/bbs/viewthread.php?tid=14414&highlight=>

 

 

Activity棧:

Android通過Activity棧的方式來管理Activity。

正在運行的Activity 處在在棧的最頂端,它是運行狀態的;

當有新Activity進入屏幕最上端時,原來的Activity就會被壓入第二層,如果他的屏幕沒有被完全遮蓋,那麼他處於Pause狀態,如果他被遮蓋那麼他處於Stop狀態。

 

當然不管你出於任何一層,都可能在系統覺得資源不足時被強行關閉,當然關閉時在棧底的程序最先被關閉。

譬如:當你在程序中調用 Activity.finish()方法時,結果和用戶按下 BACK 鍵一樣:他告訴 Activity Manager該Activity實例可以被“回收”。隨後 Activity Manager 激活處於棧第二層的 Activity 並重新入棧,把原 Activity 壓入到棧的第二層,從 Running 狀態轉到 Paused 狀態。

 

源文檔 <http://android.yaohuiji.com/archives/141>

 

 

Shutting down components

 

A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components.

Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an orderly way:

Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section,Component Lifecycles, discusses this possibility and its ramifications in more detail.

 

Why handling life-cycle events is important

If you are used to always having control in your applications, you might not understand why all this life-cycle work is necessary. The reason is that in Android, you are not in control of your Activity, the operating system is!

 

As we have already seen, the Android model is based around activities calling each other. When one Activity calls another, the current Activity is paused at the very least, and may be killed altogether if the system starts to run low on resources. If this happens, your Activity will have to store enough state to come back up later, preferably in the same state it was in when it was killed.

 

onSaveInstanceState() is called by Android if the Activity is being stopped andmay be killed before it is resumed! This means it should store any state necessary to re-initialize to the same condition when the Activity is restarted. It is the counterpart to theonCreate() method, and in fact the savedInstanceState Bundle passed in to onCreate() is the same Bundle that you construct as outState in theonSaveInstanceState() method.

 

onPause() andonResume() are also complimentary methods. onPause() is always called when the Activity ends, even if we instigated that (with a finish() call for example). We will use this to save the current note back to the database. Good practice is to release any resources that can be released during an onPause() as well, to take up less resources when in the passive state.onResume() will call our populateFields() method to read the note out of the database again and populate the fields.

 

 

In Android, an application can be “alive” even if its process has beenkilled. Put another way, the activity life cycle is not tied to the processlife cycle. Processes are just disposablecontainers for activities.

 

 

You override these methods in your Activity class, and Android will call

them at the appropriate time:

 

• onCreate(Bundle): This is called when the activity first starts up.You can use it to perform one-time initialization such as creatingthe user interface. onCreate( ) takes one parameter that is eithernull or some state information previously saved by the onSaveInstanceState(

) method.

 

• onStart( ): This indicates the activity is about to be displayed to theuser.

 

• onResume( ): This is called when your activity can start interactingwith the user. This is a good place to start animations and music.

 

• onPause( ): This runs when the activity is about to go into the background,usually because another activity has been launched infront of it. This is where you should save your program’s persistentstate, such as a database record being edited.

 

• onStop( ): This is called when your activity is no longer visible tothe user and it won’t be needed for a while. If memory is tight,onStop( ) may never be called (the system may simply terminateyour process).

 

• onRestart( ): If this method is called, it indicates your activity isbeing redisplayed to the user from a stopped state.

 

• onDestroy( ): This is called right before your activity is destroyed. Ifmemory is tight, onDestroy( ) may never be called (the system maysimply terminate your process).

 

• onSaveInstanceState(Bundle): Android will call this method to allowthe activity to save per-instance state, such as a cursor positionwithin a text field. Usually you won’t need to override it becausethe default implementation saves the state for all your user interface

controls automatically.

 

• onRestoreInstanceState(Bundle): This is called when the activity isbeing reinitialized from a state previously saved by the onSave-InstanceState( ) method. The default implementation restores thestate of your user interface.

 

 

  • Android引入了一個全新的機制-應用程序生命週期(Life Cycle)。
  • 多數情況下,一個Android應用運行在一個獨立的Linux進程中
  • 應用進程的的生命週期(存活時間)不是由進程自己控制,而是由Android系統決定
  • 影響應用生命週期的主要因素包括:該進程對於用戶的重要性,以及當前系統中還剩多少可用內存。

 

 

爲了決定在內存不足情況下消毀哪個進程,Android會根據這些進程內運行的組件及這些組件的狀態,把這些進程劃分出一個“重要性層次”。這個層次按順序如下:
       1、前端進程是擁有一個顯示在屏幕最前端並與使用者做交互的Activity(它的onResume已被調用)的進程,也可能是一個擁有正在運行的IntentReceiver(它的onReceiveIntent()方法正在運行)的進程。在系統中,這種進程是很少的,只有當內存低到不足於支持這些進程的繼續運行,纔會將這些進程消毀。通常這時候,設備已經達到了需要進行內存整理的狀態,爲了保障用戶界面不停止響應,只能消毀這些進程;
      2、可視進程是擁有一個用戶在屏幕上可見的,但並沒有在前端顯示的Activity(它的onPause已被調用)的進程。例如:一個以對話框顯示的前端activity在屏幕上顯示,而它後面的上一級activity仍然是可見的。這樣的進程是非常重要的,一般不會被消毀,除非爲了保障所有的前端進程正常運行,纔會被消毀。
       3、服務進程是擁有一個由startService()方法啓動的Service的進程。儘管這些進程對於使用者是不可見的,但他們做的通常是使用者所關注的事情(如後臺MP3播放器或後臺上傳下載數據的網絡服務)。因此,除非爲了保障前端進程和可視進程的正常運行,系統纔會消毀這種進程。
      4、後臺進程是擁有一個用戶不可見的ActivityonStop()方法已經被調用)的進程。這些進程不直接影響用戶的體驗。如果這些進程正確地完成了自己的生命週期(詳細參考Activity類),系統會爲了以上三種類型進程,而隨時消毀這種進程以釋放內存。通常會有很多這樣的進程在運行着,因些這些進程會被保存在一個LRU列表中,以保證在內存不足時,用戶最後看到的進程將在最後才被消毀。
      5、空進程是那些不擁有任何活動的應用組件的進程。保留這些進程的唯一理由是,做爲一個緩存,在它所屬的應用的組件下一次需要時,縮短啓動的時間。同樣的,爲了在這些緩存的空進程和底層的核心緩存之間平衡系統資源,系統會經常消毀這些空進程。
      當要對一個進程進行分類時,系統會選擇在這個進程中所有活動的組件中重要等級最高的那個做爲依據。可以參考ActivityServiceIntentReceiver文檔,瞭解這些組件如何影響進程整個生命週期的更多細節。這些類的文檔都對他們如何影響他們所屬的應用的整個生命週期,做了詳細的描述。

 

 

發佈了42 篇原創文章 · 獲贊 2 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章