context詳解

大家好,  今天給大家介紹下我們在應用開發中最熟悉而陌生的朋友-----Context類 ,說它熟悉,是應爲我們在開發中

  時刻的在與它打交道,例如:Service、BroadcastReceiver、Activity等都會利用到Context的相關方法 ; 說它陌生,完全是

  因爲我們真正的不懂Context的原理、類結構關係。一個簡單的問題是,一個應用程序App中存在多少個Context實例對象呢?

  一個、兩個? 在此先賣個關子吧。讀了本文,相信您會豁然開朗的 。

     Context,中文直譯爲“上下文”,SDK中對其說明如下:

Interface to global information about an application environment. This is an abstract class whose implementation

 is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls

 for application-level operations such as launching activities, broadcasting and receiving intents, etc

   從上可知一下三點,即:

   1、它描述的是一個應用程序環境的信息,即上下文。

       2、該類是一個抽象(abstract class)類,Android提供了該抽象類的具體實現類(後面我們會講到是ContextIml類)。

       3、通過它我們可以獲取應用程序的資源和類,也包括一些應用級別操作,例如:啓動一個Activity,發送廣播,接受Intent

     信息 等。。

  於是,我們可以利用該Context對象去構建應用級別操作(application-level operations) 。

一、Context相關類的繼承關係


0_1330607569Vj4c.gif

相關類介紹:

Context類    路徑: /frameworks/base/core/java/android/content/Context.java

           說明:  抽象類,提供了一組通用的API。

     源代碼(部分)如下:

  1. publicabstractclass Context {  

  2.     ...  

  3. publicabstract Object getSystemService(String name);  //獲得系統級服務

  4. publicabstractvoid startActivity(Intent intent);     //通過一個Intent啓動Activity

  5. publicabstract ComponentName startService(Intent service);  //啓動Service

  6. //根據文件名得到SharedPreferences對象

  7. publicabstract SharedPreferences getSharedPreferences(String name,int mode);  

  8.     ...  

  9. }  

ContextIml.java類  路徑 :/frameworks/base/core/java/android/app/ContextImpl.java

         說明:該Context類的實現類爲ContextIml,該類實現了Context類的功能。請注意,該函數的大部分功能都是直接調用

     其屬性mPackageInfo去完成,這點我們後面會講到。    

        源代碼(部分)如下:

  1. /**

  2. * Common implementation of Context API, which provides the base

  3. * context object for Activity and other application components.

  4. */

  5. class ContextImpl extends Context{  

  6. //所有Application程序公用一個mPackageInfo對象

  7. /*package*/ ActivityThread.PackageInfo mPackageInfo;  

  8. @Override

  9. public Object getSystemService(String name){  

  10.        ...  

  11. elseif (ACTIVITY_SERVICE.equals(name)) {  

  12. return getActivityManager();  

  13.        }  

  14. elseif (INPUT_METHOD_SERVICE.equals(name)) {  

  15. return InputMethodManager.getInstance(this);  

  16.        }  

  17.    }  

  18. @Override

  19. publicvoid startActivity(Intent intent) {  

  20.        ...  

  21. //開始啓動一個Activity

  22.        mMainThread.getInstrumentation().execStartActivity(  

  23.            getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);  

  24.    }  

  25. }  



ContextWrapper類 路徑 :\frameworks\base\core\java\android\content\ContextWrapper.java

       說明: 正如其名稱一樣,該類只是對Context類的一種包裝,該類的構造函數包含了一個真正的Context引用,即ContextIml

      對象。    源代碼(部分)如下:

  1. publicclass ContextWrapper extends Context {  

  2.    Context mBase;  //該屬性指向一個ContextIml實例,一般在創建Application、Service、Activity時賦值

  3. //創建Application、Service、Activity,會調用該方法給mBase屬性賦值

  4. protectedvoid attachBaseContext(Context base) {  

  5. if (mBase != null) {  

  6. thrownew IllegalStateException("Base context already set");  

  7.        }  

  8.        mBase = base;  

  9.    }  

  10. @Override

  11. publicvoid startActivity(Intent intent) {  

  12.        mBase.startActivity(intent);  //調用mBase實例方法

  13.    }  

  14. }  



ContextThemeWrapper類 路徑:/frameworks/base/core/java/android/view/ContextThemeWrapper.java

     說明:該類內部包含了主題(Theme)相關的接口,即android:theme屬性指定的。只有Activity需要主題,Service不需要主題,

  所以Service直接繼承於ContextWrapper類。

     源代碼(部分)如下:

  1. publicclass ContextThemeWrapper extends ContextWrapper {  

  2. //該屬性指向一個ContextIml實例,一般在創建Application、Service、Activity時賦值

  3. private Context mBase;  

  4. //mBase賦值方式同樣有一下兩種

  5. public ContextThemeWrapper(Context base, int themeres) {  

  6. super(base);  

  7.            mBase = base;  

  8.            mThemeResource = themeres;  

  9.     }  

  10. @Override

  11. protectedvoid attachBaseContext(Context newBase) {  

  12. super.attachBaseContext(newBase);  

  13.            mBase = newBase;  

  14.     }  

  15. }  


    Activity類 、Service類 、Application類本質上都是Context子類, 更多信息大家可以自行參考源代碼進行理解。


二、 什麼時候創建Context實例


     熟悉了Context的繼承關係後,我們接下來分析應用程序在什麼情況需要創建Context對象的?應用程序創建Context實例的

情況有如下幾種情況:

 1、創建Application 對象時, 而且整個App共一個Application對象

     2、創建Service對象時

     3、創建Activity對象時

   因此應用程序App共有的Context數目公式爲:

                    總Context實例個數 = Service個數 + Activity個數 + 1(Application對應的Context實例)

具體創建Context的時機

 1、創建Application對象的時機

      每個應用程序在第一次啓動時,都會首先創建Application對象。如果對應用程序啓動一個Activity(startActivity)流程比較

清楚的話,創建Application的時機在創建handleBindApplication()方法中,該函數位於 ActivityThread.java類中 ,如下:

  1. //創建Application時同時創建的ContextIml實例

  2. privatefinalvoid handleBindApplication(AppBindData data){  

  3.    ...  

  4. ///創建Application對象

  5.    Application app = data.info.makeApplication(data.restrictedBackupMode, null);  

  6.    ...  

  7. }  

  8. public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {  

  9.    ...  

  10. try {  

  11.        java.lang.ClassLoader cl = getClassLoader();  

  12.        ContextImpl appContext = new ContextImpl();    //創建一個ContextImpl對象實例

  13.        appContext.init(this, null, mActivityThread);  //初始化該ContextIml實例的相關屬性

  14. ///新建一個Application對象

  15.        app = mActivityThread.mInstrumentation.newApplication(  

  16.                cl, appClass, appContext);  

  17.       appContext.setOuterContext(app);  //將該Application實例傳遞給該ContextImpl實例        

  18.    }  

  19.    ...  

  20. }  



   2、創建Activity對象的時機

      通過startActivity()或startActivityForResult()請求啓動一個Activity時,如果系統檢測需要新建一個Activity對象時,就會

 回調handleLaunchActivity()方法,該方法繼而調用performLaunchActivity()方法,去創建一個Activity實例,並且回調

onCreate(),onStart()方法等, 函數都位於 ActivityThread.java類 ,如下:

  1. //創建一個Activity實例時同時創建ContextIml實例

  2. privatefinalvoid handleLaunchActivity(ActivityRecord r, Intent customIntent) {  

  3.    ...  

  4.    Activity a = performLaunchActivity(r, customIntent);  //啓動一個Activity

  5. }  

  6. privatefinal Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {  

  7.    ...  

  8.    Activity activity = null;  

  9. try {  

  10. //創建一個Activity對象實例

  11.        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();  

  12.        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);  

  13.    }  

  14. if (activity != null) {  

  15.        ContextImpl appContext = new ContextImpl();      //創建一個Activity實例

  16.        appContext.init(r.packageInfo, r.token, this);   //初始化該ContextIml實例的相關屬性

  17.        appContext.setOuterContext(activity);            //將該Activity信息傳遞給該ContextImpl實例

  18.        ...  

  19.    }  

  20.    ...      

  21. }  


3、創建Service對象的時機

      通過startService或者bindService時,如果系統檢測到需要新創建一個Service實例,就會回調handleCreateService()方法,

完成相關數據操作。handleCreateService()函數位於 ActivityThread.java類,如下:

  1. //創建一個Service實例時同時創建ContextIml實例

  2. privatefinalvoid handleCreateService(CreateServiceData data){  

  3.    ...  

  4. //創建一個Service實例

  5.    Service service = null;  

  6. try {  

  7.        java.lang.ClassLoader cl = packageInfo.getClassLoader();  

  8.        service = (Service) cl.loadClass(data.info.name).newInstance();  

  9.    } catch (Exception e) {  

  10.    }  

  11.    ...  

  12.    ContextImpl context = new ContextImpl(); //創建一個ContextImpl對象實例

  13.    context.init(packageInfo, null, this);   //初始化該ContextIml實例的相關屬性

  14. //獲得我們之前創建的Application對象信息

  15.    Application app = packageInfo.makeApplication(false, mInstrumentation);  

  16. //將該Service信息傳遞給該ContextImpl實例

  17.    context.setOuterContext(service);  

  18.    ...  

  19. }  


另外,需要強調一點的是,通過對ContextImp的分析可知,其方法的大多數操作都是直接調用其屬性mPackageInfo(該屬性類

型爲PackageInfo)的相關方法而來。這說明ContextImp是一種輕量級類,而PackageInfo纔是真正重量級的類。而一個App裏的

有ContextIml實例,都對應同一個packageInfo對象。

    最後給大家分析利用Context獲取SharedPreferences類的使用方法,SharedPreferences類想必大家都使用過,其一般獲取方

法就是通過調用getSharedPreferences()方法去根據相關信息獲取SharedPreferences對象。具體流程如下:


   1 、調用  getSharedPreferences()獲取對應的的文件,該函數實現功能如下:

  1. //Context類靜態數據集合,以鍵值對保存了所有讀取該xml文件後所形成的數據集合

  2. privatestaticfinal HashMap<File, SharedPreferencesImpl> sSharedPrefs =  

  3. new HashMap<File, SharedPreferencesImpl>();  

  4. @Override

  5. public SharedPreferences getSharedPreferences(String name, int mode){  

  6. //其所對應的SharedPreferencesImpl對象 ,該對象已一個HashMap集合保存了我們對該文件序列化結果

  7.     SharedPreferencesImpl sp;    

  8.     File f = getSharedPrefsFile(name);  //該包下是否存在對應的文件,不存在就新建一個

  9. synchronized (sSharedPrefs) {       //是否已經讀取過該文件,是就直接返回該SharedPreferences對象

  10.         sp = sSharedPrefs.get(f);  

  11. if (sp != null && !sp.hasFileChanged()) {  

  12. //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);

  13. return sp;  

  14.         }  

  15.     }  

  16. //以下爲序列化該xml文件,同時將數據寫到map集合中    

  17.     Map map = null;  

  18. if (f.exists() && f.canRead()) {  

  19. try {  

  20.             str = new FileInputStream(f);  

  21.             map = XmlUtils.readMapXml(str);  

  22.             str.close();  

  23.         }  

  24.         ...  

  25.     }  

  26. synchronized (sSharedPrefs) {  

  27. if (sp != null) {  

  28. //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);

  29.             sp.replace(map);   //更新數據集合

  30.         } else {  

  31.             sp = sSharedPrefs.get(f);  

  32. if (sp == null) {    

  33. //新建一個SharedPreferencesImpl對象,並且設置其相關屬性

  34.                 sp = new SharedPreferencesImpl(f, mode, map);    

  35.                 sSharedPrefs.put(f, sp);  

  36.             }  

  37.         }  

  38. return sp;  

  39.     }  

  40. }  


  2、 SharedPreferences 不過是個接口,它定義了一些操作xml文件的方法,其真正實現類爲SharedPreferencesImpl ,該類是

   ContextIml的內部類,該類如下:

  1. //soga,這種形式我們在分析Context ContextIml時接觸過

  2. //SharedPreferences只是一種接口,其真正實現類是SharedPreferencesImpl類

  3. privatestaticfinalclass SharedPreferencesImpl implements SharedPreferences{  

  4. private Map mMap;  //保存了該文件序列化結果後的操作, 鍵值對形式

  5. //通過key值獲取對應的value值

  6. public String getString(String key, String defValue) {  

  7. synchronized (this) {  

  8.             String v = (String)mMap.get(key);  

  9. return v != null ? v : defValue;  

  10.         }  

  11.     }  

  12.     ...  

  13. //獲得該SharedPreferencesImpl對象對應的Edito類,對數據進行操作

  14. publicfinalclass EditorImpl implements Editor {  

  15. privatefinal Map<String, Object> mModified = Maps.newHashMap(); //保存了對鍵值變化的集合

  16.     }  

  17. }  




      基本上獲取SharedPreferences 對象就是這麼來的,關於Context裏的更多方法請大家參照源代碼認真學習吧。


本文轉載於:http://blog.csdn.net/qinjuning

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章