Activity生命週期回調函數以及應用場景

先看一下Activity的生命週期圖:


瞭解Activity生命週期的意義:

官網描述(http://developer.android.com/guide/components/activities.html):    

   When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—andeach callback provides you the opportunity to perform specific work that's appropriate to that state change. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle.

   意義:每個回調函數爲Activity提供了在狀態改變時爲應用做一些特定處理的時機。


Managing the Activity Lifecycle

   Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible application. The lifecycle of an activity is directly affected by its association with other activities, its task and back stack.

  An activity can exist in essentially three states:

Resumed
The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)
Paused
Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity iscompletely alive (the Activity object isretained in memory, it maintains all state and member information, and remains attached to the window manager),but can be killed by the system in extremely low memory situations.
Stopped
The activity is completely obscured(遮蔽的;湮沒的) by another activity (the activity is now in the "background"). A stopped activity is alsostill alive (the Activity object isretained in memory, it maintains all state andmember information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.

   If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish() method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.

處於Paused和Stopped狀態的Activity仍然alive,保存在內存中,並且只有之前的狀態和信息。所以當Activity跳轉到新的Activity界面、按Home鍵回到主屏、按鎖屏鍵、設備休眠,這些情況下(均爲Stopped狀態)再返回原來的Activity時,Activity之前的狀態和信息還在。內存不足時回收內存時除外。

 The two most important callback methods are:

onCreate()
You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.
onPause()
The system calls this method as the first indication(指示,指出;跡象;象徵) that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).


Note: Your implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above.


  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread inonDestroy().
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart()to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.


A summary of the activity lifecycle's callback methods.

Method Description Killable after? Next
onCreate() Called when the activity is first created. This is where you should do all of your normal static set up — create views, bind data to lists, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured (see Saving Activity State, later).

Always followed by onStart().

No onStart()
  onRestart() Called after the activity has been stopped, just prior to it being started again.

Always followed by onStart()

No onStart()
onStart() Called just before the activity becomes visible to the user.

Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

No onResume() 
or
onStop()
  onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

No onPause()
onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.

Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user.

Yes onResume() 
or
onStop()
onStop() Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.

Followed either by onRestart() if the activity is coming back to interact with the user, or byonDestroy() if this activity is going away.

Yes onRestart()
or
onDestroy()
onDestroy() Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Yes nothing


Shutting Down an Activity

You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().

Note: In most cases, you should not explicitly finish an activity using these methods. The Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.


Saving activity state

處於Paused和Stopped狀態的Activity仍然alive,保存在內存中,並且只有之前的狀態和信息。所以當Activity跳轉到新的Activity界面、按Home鍵回到主屏、按鎖屏鍵、設備休眠,這些情況下(均爲Stopped狀態)再返回原來的Activity時,Activity之前的狀態和信息還在。內存不足時回收內存時除外。

在Activity被Destory後,需要保存Activity信息時,需要調用 onSaveInstanceState()方法。

The system calls onSaveInstanceState() before making the activity vulnerable( 易受攻擊的,易受…的攻擊;易受傷害的;有弱點的) to destruction(破壞). The system passes this method a Bundle in which you can save state information about the activity as name-value pairs, using methods such as putString() and putInt(). Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes the Bundle to both onCreate()and onRestoreInstanceState(). Using either of these methods, you can extract your saved state from the Bundle and restore the activity state. If there is no state information to restore, then the Bundle passed to you is null (which is the case when the activity is created for the first time).



Note: There'sno guarantee that onSaveInstanceState() will be called before your activity is destroyed, because there are cases in which it won't be necessary to save the state (such as when the user leaves your activity using the Back button, because the user is explicitly closing the activity). If the system calls onSaveInstanceState(), it does so before onStop() and possibly before onPause().

onSaveInstanceState()方法不保證一定會在Activity銷燬之前執行,onSaveInstanceState的調用遵循一個重要原則,即當系統“未經你許可”時銷燬了你的activity(不是自己主動銷燬activity),則onSaveInstanceState會被系統調用。

onSaveInstanceState()方法的執行順序可能在onStop()方法之前,也可能在onPause()方法之前。

However, even if you do nothing and do not implement onSaveInstanceState(),some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation calls the corresponding onSaveInstanceState() method for every View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

如果不需要保存額外的信息,可以不是實現onSaveInstanceState()方法,Activity會調用默認的onSaveInstanceState()方法來保存Activity的狀態信息,默認的onSaveInstanceState()方法會調用Layout中每個View的相關onSaveInstanceState()方法來保存View自己的信息,幾乎每個Widget都實現了onSaveInstanceState()方法來保存自己的狀態信息。必須爲Widget設置ID,系統此後保存該Widget的狀態信息。


You can also explicitly stop a view in your layout from saving its state by setting the android:saveEnabled attribute to "false" or by calling the setSaveEnabled() method. Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently.


Because the default implementation of onSaveInstanceState()helps save the state of the UI, if you override the method in order to save additional state information, you should alwayscall the superclass implementation of onSaveInstanceState() before doing any work. Likewise, youshould also call the superclass implementation of onRestoreInstanceState() if you override it, so the default implementation can restore view states.




Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only torecord the transient(短暫的) state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.

因爲onSaveInstanceState()方法不保證會一定執行,所以應只使用該方法來保存Ativity瞬時短暫的狀態信息(UI的狀態),不用用該方法來保存持久化的數據,應該使用onPause()方法來保存持久化數據,例如存入數據庫的數據。


Handling configuration changes

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android recreates the running activity (the system calls onDestroy(), then immediately calls onCreate()). 

The best way to handle such a restart is to save and restore the state of your activity using onSaveInstanceState() and onRestoreInstanceState() (or onCreate()), as discussed in the previous section.


Coordinating activities

When one activity starts another, they both experience(經歷,體驗) lifecycle transitions(轉變). The first activity pauses and stops (though, it won't stop if it's still visible in the background), while the other activity is created. In case these activities share data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps(重疊) with the process of stopping the first one.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here's the order of operations that occur when Activity A starts Acivity B:

  1. Activity A's onPause() method executes.
  2. Activity B's onCreate()onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. Then, if Activity A is no longer visible on screen, its onStop() method executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example,if you must write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of during onStop().




應用場景:

1、onCreate(): The activity is being created.

在完整生命週期開始時調用。

執行一些在Activity生命週期只執行一次的基本的應用啓動邏輯。

(1)、必須實現的方法,系統在開始創建Activity的時候調用該方法,該方法應該初始化Activity中的組件,最重要的是,要調用setContentView()方法來爲Activity界面定義佈局;

(2)、定義全局的狀態信息(例如Layout),得到Fragment的引用;

(3)、分配對類變量的引用,初始化類變量;

(4)、將數據綁定到控件;

(5)、啓動Service和定時器;

(6)、開啓線程,如果需要的話;

(7)、通過Bundle參數保存的數據恢復被Kill掉的Activity的(onSaveInstanceState()方法中保存)狀態信息。也可在onRestoreInstanceState()方法中恢復。

(8)、屏幕旋轉時恢復onRestoreInstanceState()保存的Activity的信息。也可在onRestoreInstanceState()方法中恢復。

       作爲使用Android變形高效代碼的指導原則的一部分,我們建議最好避免創建短期的對象。對象的快速創建和銷燬會導致額外的垃圾收集過程,而這個過程會對用戶體驗產生直接的影響。如果Activity是有規律的創建相同的對象集,那麼可以考慮在onCreate方法中創建他們,因爲它只在Activity的生存期中被調用一次。


2、onRestart():裝載改變,知道Activity在此進程中已經可見。

(1)、恢復在onStop()方法中暫停或停止的Service或者其他專門用於更新用戶界面的進程。

(2)、實現那些只有當Activity在它的完整生存期之內重啓時才能完成的特殊處理。

   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.
   you should usually use the onStart() callback method as the counterpart(配對) to the onStop() method, because the system calls onStart() both when it creates your activity and when it restarts the activity from the stopped state.



3、onStart()The activity is about to become visible.

在可見生存週期開始的時候調用。既然Activity可見,就可以應用任何的UI改變。

(1)、維持需要展示的資源(maintain resources that are needed to show the activity to the user),例如註冊 BroadcastReceiver

(2)、改變UI。

(3)、恢復在onStop()方法中暫停或停止的Service或者其他專門用於更新用戶界面的進程。


4、onResume()The activity has become visible (it is now "resumed").

在Activity狀態生存週期開始時調用。恢復當Activity處於不活動狀態時被掛起的暫停的UI更新、線程或進程。

(1)、foreground生命週期狀態會經常的改變,所以onResume()和onPause()方法做一些非常輕量級的工作,防止界面經常延遲等待。

(2)、恢復當Activity處於不活動狀態時被掛起的暫停的UI更新、線程或進程。

Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time. As such, you should implement onResume() to initialize components that you release during onPause() and perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).



5、onPause()Another activity is taking focus (this activity is about to be "paused").

在Activity狀態生存週期結束時調用。掛起不需要更新的UI更新、線程或者CPU密集的進程。

(1)、foreground生命週期狀態會經常的改變,所以onResume()和onPause()方法做一些非常輕量級的工作,防止界面經常延遲等待。

(2)、系統調用該方法作爲用戶即將離開該Activity時的第一個跡象。該方法中通常應該處理當前用戶回話中需要提交保存的改變(例如數據),因爲用戶可能不會再回到該界面。

(3)、保存需要存儲到數據庫中的持久化數據。

(4)、掛起不需要更新的UI更新、線程或者CPU密集的進程。

You should usually use the onPause() callback to:

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

For example, if your application uses the Camera, the onPause() method is a good place to release it.

   Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage withinonPause() is when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).


6、onStop()The activity is no longer visible (it is now "stopped")

在可見生存週期結束時調用。掛起不要的UI更新、線程或處理。當Activity不可見時,保存所有的編輯或者狀態改變,因爲調用這個方法後,進程可能會被終止。

(1)、unregister BroadcastReceiver

(2)、掛起不要的UI更新、線程或處理。

(3)、保存所有的編輯或者狀態改變。

(4)、暫停或停止動畫;

(5)、暫停或停止傳感器監聽器;

(6)、暫停或停止GPS查找;

(7)、暫停或停止定位器;

(8)、暫停或停止Service或者其他專門用於更新用戶界面的進程,當UI不可見的時候更新它是沒有意義的。

(9)、保存需要存儲到數據庫中的持久化數據。


   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.
    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.
    When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to(leading up to:在…之前) the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.




7、onDestroy()The activity is about to be destroyed.

在完整生存週期結束時調用。清理所有的資源,包括結束線程、關閉數據庫連接等。

   The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.

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

(1)、釋放所有的持有的資源;

(2)、關閉開啓的線程;

(3)、關閉數據庫連接;

(4)、關閉網絡連接。


8、onSaveInstanceState():保存Activity狀態。

把UI狀態改變保存到該方法中。

(1)、save additional information

Although the default implementation of onSaveInstanceState()saves useful information about your activity's UI, you still might need to override it to save additional information. For example, you might need to save member values that changed during the activity's life (which might correlate to values restored in the UI, but the members that hold those UI values are not restored, by default).

     如果實現了該方法來保存額外的信息,如果還想使用默認的onSaveInstanceState()方法保存Activity信息(推薦),首先要調用父類的onSaveInstanceState()方法。

(2)、因爲onSaveInstanceState()方法不保證會一定執行,所以應只使用該方法來保存Ativity瞬時的、短暫的UI的狀態信息,不用用該方法來保存持久化的數據,應該使用onPause()方法來保存持久化數據,例如存入數據庫的數據。

(3)、屏幕旋轉時保存Activity的信息。


9、onRestoreInstanceState()

用於恢復UI狀態,只有當系統終止了該Activity後再次重新創建後,纔會調用該方法。

(1)、通過Bundle參數保存的數據恢復被Kill掉的Activity的(onSaveInstanceState()方法中保存)狀態信息。也可在onCreate()方法中恢復。

如下實現了該方法來恢復保存額外的信息,如果想使用默認的onRestoreInstanceState()方法來恢復保存Activity信息(推薦),首先要調用父類的onRestoreInstanceState()方法。

(2)、屏幕旋轉時恢復onRestoreInstanceState()保存的Activity的信息。也可在onCreate()方法中恢復。



   當然,以上的場景只是通常的情況下,每個回調函數中需要做的事情,具體的情況需要具體分析,在合適的時機調用對應的回調函數。

參考原文:http://developer.android.com/guide/components/activities.html#Lifecycle
《Android 4 高級編程(第3版)》
發佈了10 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章