在代碼中經常看到application這個類,一直不知道這個是幹什麼用的,今天剛好有點時間,所以進行了詳細的學習。
一.先對它的整體概念解釋:
在android源碼中對他的描述是;
* Base class for those who need to maintain global application state. You can
* provide your own implementation by specifying its name in your
* AndroidManifest.xml's <application> tag, which will cause that class
* to be instantiated for you when the process for your application/package is
* created.
SDK中的描述:Application類是爲了那些需要保存全局變量設計的基本類,你可以在AndroidManifest.xml的<application>標籤中進行自己的實現,這樣的結果是:當你的 application或者包被建立的時候將引起那個類被建立。
理解:就是說application是用來保存全局變量的,並且是在package創建的時候就跟着存在了。所以當我們需要創建全局變量的時候,不需 要再像j2se那樣需要創建public權限的static變量,而直接在application中去實現。只需要調用Context的getApplicationContext或者Activity的getApplication方法來獲得一個application對象,再做出相應 的處理。
例如Launcher模塊中;它自己就寫了個application,在AndroidManifest.xml中將它進行了設置:
<application
android:name="com.android.launcher2.LauncherApplication"
對於他的設置可以參考這個模塊。
二.裏面的方法進行說明:
onCreate();
/**
* Called when the application is starting, before any other application
* objects have been created. Implementations should be as quick as
* possible (for example using lazy initialization of state) since the time
* spent in this function directly impacts the performance of starting the
* first activity, service, or receiver in a process.
* If you override this method, be sure to call super.onCreate().
*/
這個函數是當我們的應用開始之時就被調用了,比應用中的其他對象創建的早,這個實現儘可能的快一點,因爲這個時間直接影響到我們第一個activity/service
/receiver。如果你要重寫這個方法必須調用super.onCreate().
onTerminate():
/**
* This method is for use in emulated process environments. It will
* never be called on a production Android device, where processes are
* removed by simply killing them; no user code (including this callback)
* is executed when doing so.
*/
這個函數是模擬一個過程環境,在真機中永遠也不會被調用。