Android Context原理與使用的總結

來源:互聯網
上載者:User

標籤:



一、Context繼承體系 與 Context是如何建立的1. Context繼承體系
只用記住一句:Activity 、 Service 與Application 都是繼承自ContextWrapper,而ContextWrapper implements Context。每個:Activity 、 Service 與Application都是一個Context執行個體。

2. Context 何時建立、怎樣建立的 - 查看源碼
Android應用程式視窗(Activity)的運行上下文環境(Context)的建立過程分析

Android 核心--Context對象

Android中Context詳解 ---- 你所不知道的Context
以上3篇文章都是從源碼角度分析Context何時建立的,但是對於平時的開發來說,僅需要知道Activity 與Service 都是繼承自Context,只要建立新的Activity 或者 Service 執行個體,都是建立新的Context執行個體。
Context 總數 = Activity個數 + Service 個數 + 1個ApplicationContext
可以通過命令列 查看Context的個數
adb shell dumpsys meminfo package_name


二、關於Context的疑問1. getBaseContext 與 getApplicationContext 區別?持有Activity的Context 相當於持有Context,而持有AppliactionContex全域僅有這一個
2. 視圖中的Context從哪來的?例如:new TextView(Context);
通常在一個Activity中傳入的就是當前Activity或者Activity.getBaseContext(),所以通過View.getContext()其實就是當前Activity的引用。
常見情境,Adapter通常通過構造器傳遞Context,用於getView 時inflate 視圖。但是getView最有一個參數是parentView 這個是ListView對象本身,可以通過parentView.getContext擷取Context對象減少手動傳遞。
3. Context 會出錯的地方Dialog.Builder必須傳入Activity,而不能傳入Activity.getApplicationContext()
4. Context作用,查看方法訪問資源、建立視圖、建立四大組件
Context是什嗎?

參考資料: Android源碼分析-全面理解ContextAndroid中Context的總結及其用法

三 記憶體溢出,因為引用Context導致1. Context導致記憶體溢出的原因:Avoiding memory leaks 、 Avoiding memory leaks
Android - what‘s the difference between the various methods to get a Context?

以上文章講解的很詳細可以查看文章,以下是簡單描述:最常見的記憶體形式是Bitmap未得到釋放,而圖片通常ImageView持有導致ImageView也不會被GC釋放,建立ImageView肯定需要Context,這個Context是Activity。Bitmap -> ImageView -> Contex(Activity)如果Activity總是不能得到釋放,導致記憶體不足最終OOM

2. 對於生命週期很長的對象,使用ApplicationContext,以下文檔介紹自訂Application可以在項目全域都很方便擷取Application Context的方法
使用自訂Application,需要Context對象時傳入,避免因持有Context導致的記憶體溢出。因為ApplicationContext全域僅有一個執行個體,而多個Activity本身繼承自Context,就是多個Context執行個體。
Android中Activity共用變數的另一方法:Application context
談談Android裡的Context的使用!!!

4. Context記憶體溢出相關資料Android學習系列(36)--App調試記憶體泄露之Context篇(上)
Android學習系列(37)--App調試記憶體泄露之Context篇(下)

四、自己建立ContextAndroid擷取其他包的Context執行個體然後幹壞事http://chroya.iteye.com/blog/761441



Android Context原理與使用的總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.