1. 程式人生 > >ApplicationContext和Context

ApplicationContext和Context

1. 當使用 LayoutInflater 從 xml 檔案中 inflate 佈局時,呼叫的是 View(Context,AttributeSet) 建構函式,使用的 Context 例項跟 LayoutInflater 建立時使用的 Context 一樣,並且 LayoutInflater 會快取在 Context 例項中,即相同的 Context 例項多次呼叫會獲取一樣的 LayoutInflater 例項。

2. Activity Context 會讀取 Theme 的樣式資訊,而 Application Context 則不會。

 

getApplicationContext() 的存在是 Android 歷史原因,getApplication() 這個只存在 Activity 和 Service 類中,那麼對於 BroadcastReceiver 和 ContentProvider 來說,要獲取 Application,就只能通過 getApplicationContext()。

1.對於 Activity/Service 來說,這兩個方法沒有區別,除非廠商修改過

2.BroadcastReceiver 只能通過 getApplicationContext() 獲取 Application 例項

3.ContentProvider 也只能通過 getApplicationContext() 獲取 Application 例項,但有可能出現空值的情況。當同個程序有多個 apk 的情況下,對於第二個 apk 是由 provider 方式拉起,而 provider 建立過程中並不會初始化 Application,此時呼叫 getApplicationContext() 則會返回空。