轉(zhuǎn)載必須注明出處 :http://blog.csdn.net/qinjuning
前言:本文是我讀《Android內(nèi)核剖析》第7章 后形成的讀書筆記 ,在此向欲了解Android框架的書籍推薦此書。
大家好, 今天給大家介紹下我們在應(yīng)用開發(fā)中最熟悉而陌生的朋友-----Context類 ,說它熟悉,是應(yīng)為我們在開發(fā)中
時刻的在與它打交道,例如:Service、BroadcastReceiver、Activity等都會利用到Context的相關(guān)方法 ; 說它陌生,完全是
因為我們真正的不懂Context的原理、類結(jié)構(gòu)關(guān)系。一個簡單的問題是,一個應(yīng)用程序App中存在多少個Context實例對象呢?
一個、兩個? 在此先賣個關(guān)子吧。讀了本文,相信您會豁然開朗的 。
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、它描述的是一個應(yīng)用程序環(huán)境的信息,即上下文。
2、該類是一個抽象(abstract class)類,Android提供了該抽象類的具體實現(xiàn)類(后面我們會講到是ContextIml類)。
3、通過它我們可以獲取應(yīng)用程序的資源和類,也包括一些應(yīng)用級別操作,例如:啟動一個Activity,發(fā)送廣播,接受Intent
信息 等。。
于是,我們可以利用該Context對象去構(gòu)建應(yīng)用級別操作(application-level operations) 。
一、Context相關(guān)類的繼承關(guān)系

相關(guān)類介紹:
Context類 路徑: /frameworks/base/core/java/android/content/Context.java
說明: 抽象類,提供了一組通用的API。
源代碼(部分)如下:
- public abstract class Context {
- ...
- public abstract Object getSystemService(String name); //獲得系統(tǒng)級服務(wù)
- public abstract void startActivity(Intent intent); //通過一個Intent啟動Activity
- public abstract ComponentName startService(Intent service); //啟動Service
- //根據(jù)文件名得到SharedPreferences對象
- public abstract SharedPreferences getSharedPreferences(String name,int mode);
- ...
- }
ContextIml.java類 路徑 :/frameworks/base/core/java/android/app/ContextImpl.java
說明:該Context類的實現(xiàn)類為ContextIml,該類實現(xiàn)了Context類的功能。請注意,該函數(shù)的大部分功能都是直接調(diào)用
其屬性mPackageInfo去完成,這點我們后面會講到。
源代碼(部分)如下:
- /**
- * Common implementation of Context API, which provides the base
- * context object for Activity and other application components.
- */
- class ContextImpl extends Context{
- //所有Application程序公用一個mPackageInfo對象
- /*package*/ ActivityThread.PackageInfo mPackageInfo;
-
- @Override
- public Object getSystemService(String name){
- ...
- else if (ACTIVITY_SERVICE.equals(name)) {
- return getActivityManager();
- }
- else if (INPUT_METHOD_SERVICE.equals(name)) {
- return InputMethodManager.getInstance(this);
- }
- }
- @Override
- public void startActivity(Intent intent) {
- ...
- //開始啟動一個Activity
- mMainThread.getInstrumentation().execStartActivity(
- getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
- }
- }
ContextWrapper類 路徑 :\frameworks\base\core\java\android\content\ContextWrapper.java
說明: 正如其名稱一樣,該類只是對Context類的一種包裝,該類的構(gòu)造函數(shù)包含了一個真正的Context引用,即ContextIml
對象。 源代碼(部分)如下:
- public class ContextWrapper extends Context {
- Context mBase; //該屬性指向一個ContextIml實例,一般在創(chuàng)建Application、Service、Activity時賦值
-
- //創(chuàng)建Application、Service、Activity,會調(diào)用該方法給mBase屬性賦值
- protected void attachBaseContext(Context base) {
- if (mBase != null) {
- throw new IllegalStateException("Base context already set");
- }
- mBase = base;
- }
- @Override
- public void startActivity(Intent intent) {
- mBase.startActivity(intent); //調(diào)用mBase實例方法
- }
- }
ContextThemeWrapper類 路徑:/frameworks/base/core/java/android/view/ContextThemeWrapper.java
說明:該類內(nèi)部包含了主題(Theme)相關(guān)的接口,即android:theme屬性指定的。只有Activity需要主題,Service不需要主題,
所以Service直接繼承于ContextWrapper類。
源代碼(部分)如下:
- public class ContextThemeWrapper extends ContextWrapper {
- //該屬性指向一個ContextIml實例,一般在創(chuàng)建Application、Service、Activity時賦值
-
- private Context mBase;
- //mBase賦值方式同樣有一下兩種
- public ContextThemeWrapper(Context base, int themeres) {
- super(base);
- mBase = base;
- mThemeResource = themeres;
- }
-
- @Override
- protected void attachBaseContext(Context newBase) {
- super.attachBaseContext(newBase);
- mBase = newBase;
- }
- }
Activity類 、Service類 、Application類本質(zhì)上都是Context子類, 更多信息大家可以自行參考源代碼進行理解。
二、 什么時候創(chuàng)建Context實例
熟悉了Context的繼承關(guān)系后,我們接下來分析應(yīng)用程序在什么情況需要創(chuàng)建Context對象的?應(yīng)用程序創(chuàng)建Context實例的
情況有如下幾種情況:
1、創(chuàng)建Application 對象時, 而且整個App共一個Application對象
2、創(chuàng)建Service對象時
3、創(chuàng)建Activity對象時
因此應(yīng)用程序App共有的Context數(shù)目公式為:
總Context實例個數(shù) = Service個數(shù) + Activity個數(shù) + 1(Application對應(yīng)的Context實例)
具體創(chuàng)建Context的時機
1、創(chuàng)建Application對象的時機
每個應(yīng)用程序在第一次啟動時,都會首先創(chuàng)建Application對象。如果對應(yīng)用程序啟動一個Activity(startActivity)流程比較
清楚的話,創(chuàng)建Application的時機在創(chuàng)建handleBindApplication()方法中,該函數(shù)位于 ActivityThread.java類中 ,如下:
- //創(chuàng)建Application時同時創(chuàng)建的ContextIml實例
- private final void handleBindApplication(AppBindData data){
- ...
- ///創(chuàng)建Application對象
- Application app = data.info.makeApplication(data.restrictedBackupMode, null);
- ...
- }
-
- public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
- ...
- try {
- java.lang.ClassLoader cl = getClassLoader();
- ContextImpl appContext = new ContextImpl(); //創(chuàng)建一個ContextImpl對象實例
- appContext.init(this, null, mActivityThread); //初始化該ContextIml實例的相關(guān)屬性
- ///新建一個Application對象
- app = mActivityThread.mInstrumentation.newApplication(
- cl, appClass, appContext);
- appContext.setOuterContext(app); //將該Application實例傳遞給該ContextImpl實例
- }
- ...
- }
2、創(chuàng)建Activity對象的時機
通過startActivity()或startActivityForResult()請求啟動一個Activity時,如果系統(tǒng)檢測需要新建一個Activity對象時,就會
回調(diào)handleLaunchActivity()方法,該方法繼而調(diào)用performLaunchActivity()方法,去創(chuàng)建一個Activity實例,并且回調(diào)
onCreate(),onStart()方法等, 函數(shù)都位于 ActivityThread.java類 ,如下:
- //創(chuàng)建一個Activity實例時同時創(chuàng)建ContextIml實例
- private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity a = performLaunchActivity(r, customIntent); //啟動一個Activity
- }
- private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity activity = null;
- try {
- //創(chuàng)建一個Activity對象實例
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
- }
- if (activity != null) {
- ContextImpl appContext = new ContextImpl(); //創(chuàng)建一個Activity實例
- appContext.init(r.packageInfo, r.token, this); //初始化該ContextIml實例的相關(guān)屬性
- appContext.setOuterContext(activity); //將該Activity信息傳遞給該ContextImpl實例
- ...
- }
- ...
- }
3、創(chuàng)建Service對象的時機
通過startService或者bindService時,如果系統(tǒng)檢測到需要新創(chuàng)建一個Service實例,就會回調(diào)handleCreateService()方法,
完成相關(guān)數(shù)據(jù)操作。handleCreateService()函數(shù)位于 ActivityThread.java類,如下:
- //創(chuàng)建一個Service實例時同時創(chuàng)建ContextIml實例
- private final void handleCreateService(CreateServiceData data){
- ...
- //創(chuàng)建一個Service實例
- Service service = null;
- try {
- java.lang.ClassLoader cl = packageInfo.getClassLoader();
- service = (Service) cl.loadClass(data.info.name).newInstance();
- } catch (Exception e) {
- }
- ...
- ContextImpl context = new ContextImpl(); //創(chuàng)建一個ContextImpl對象實例
- context.init(packageInfo, null, this); //初始化該ContextIml實例的相關(guān)屬性
- //獲得我們之前創(chuàng)建的Application對象信息
- Application app = packageInfo.makeApplication(false, mInstrumentation);
- //將該Service信息傳遞給該ContextImpl實例
- context.setOuterContext(service);
- ...
- }
另外,需要強調(diào)一點的是,通過對ContextImp的分析可知,其方法的大多數(shù)操作都是直接調(diào)用其屬性mPackageInfo(該屬性類
型為PackageInfo)的相關(guān)方法而來。這說明ContextImp是一種輕量級類,而PackageInfo才是真正重量級的類。而一個App里的
所有ContextIml實例,都對應(yīng)同一個packageInfo對象。
最后給大家分析利用Context獲取SharedPreferences類的使用方法,SharedPreferences類想必大家都使用過,其一般獲取方
法就是通過調(diào)用getSharedPreferences()方法去根據(jù)相關(guān)信息獲取SharedPreferences對象。具體流程如下:
1 、調(diào)用 getSharedPreferences()獲取對應(yīng)的的文件,該函數(shù)實現(xiàn)功能如下:
- //Context類靜態(tài)數(shù)據(jù)集合,以鍵值對保存了所有讀取該xml文件后所形成的數(shù)據(jù)集合
- private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =
- new HashMap<File, SharedPreferencesImpl>();
-
- @Override
- public SharedPreferences getSharedPreferences(String name, int mode){
- //其所對應(yīng)的SharedPreferencesImpl對象 ,該對象已一個HashMap集合保存了我們對該文件序列化結(jié)果
- SharedPreferencesImpl sp;
- File f = getSharedPrefsFile(name); //該包下是否存在對應(yīng)的文件,不存在就新建一個
- synchronized (sSharedPrefs) { //是否已經(jīng)讀取過該文件,是就直接返回該SharedPreferences對象
- sp = sSharedPrefs.get(f);
- if (sp != null && !sp.hasFileChanged()) {
- //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
- return sp;
- }
- }
- //以下為序列化該xml文件,同時將數(shù)據(jù)寫到map集合中
- Map map = null;
- if (f.exists() && f.canRead()) {
- try {
- str = new FileInputStream(f);
- map = XmlUtils.readMapXml(str);
- str.close();
- }
- ...
- }
-
- synchronized (sSharedPrefs) {
- if (sp != null) {
- //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);
- sp.replace(map); //更新數(shù)據(jù)集合
- } else {
- sp = sSharedPrefs.get(f);
- if (sp == null) {
- //新建一個SharedPreferencesImpl對象,并且設(shè)置其相關(guān)屬性
- sp = new SharedPreferencesImpl(f, mode, map);
- sSharedPrefs.put(f, sp);
- }
- }
- return sp;
- }
- }
2、 SharedPreferences 不過是個接口,它定義了一些操作xml文件的方法,其真正實現(xiàn)類為SharedPreferencesImpl ,該類是
ContextIml的內(nèi)部類,該類如下:
- //soga,這種形式我們在分析Context ContextIml時接觸過
- //SharedPreferences只是一種接口,其真正實現(xiàn)類是SharedPreferencesImpl類
- private static final class SharedPreferencesImpl implements SharedPreferences{
- private Map mMap; //保存了該文件序列化結(jié)果后的操作, 鍵值對形式
-
- //通過key值獲取對應(yīng)的value值
- public String getString(String key, String defValue) {
- synchronized (this) {
- String v = (String)mMap.get(key);
- return v != null ? v : defValue;
- }
- }
- ...
- //獲得該SharedPreferencesImpl對象對應(yīng)的Edito類,對數(shù)據(jù)進行操作
- public final class EditorImpl implements Editor {
- private final Map<String, Object> mModified = Maps.newHashMap(); //保存了對鍵值變化的集合
- }
- }
基本上獲取SharedPreferences 對象就是這么來的,關(guān)于Context里的更多方法請大家參照源代碼認真學(xué)習(xí)吧。