轉(zhuǎn)載必須注明出處 :http://blog.csdn.net/qinjuning
前言:本文是我讀《Android內(nèi)核剖析》第7章 后形成的讀書筆記 ,在此向欲了解Android框架的書籍推薦此書。
大家好, 今天給大家介紹下我們?cè)趹?yīng)用開發(fā)中最熟悉而陌生的朋友-----Context類 ,說它熟悉,是應(yīng)為我們?cè)陂_發(fā)中
時(shí)刻的在與它打交道,例如:Service、BroadcastReceiver、Activity等都會(huì)利用到Context的相關(guān)方法 ; 說它陌生,完全是
因?yàn)槲覀冋嬲牟欢瓹ontext的原理、類結(jié)構(gòu)關(guān)系。一個(gè)簡(jiǎn)單的問題是,一個(gè)應(yīng)用程序App中存在多少個(gè)Context實(shí)例對(duì)象呢?
一個(gè)、兩個(gè)? 在此先賣個(gè)關(guān)子吧。讀了本文,相信您會(huì)豁然開朗的 。
Context,中文直譯為“上下文”,SDK中對(duì)其說明如下:
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
從上可知一下三點(diǎn),即:
1、它描述的是一個(gè)應(yīng)用程序環(huán)境的信息,即上下文。
2、該類是一個(gè)抽象(abstract class)類,Android提供了該抽象類的具體實(shí)現(xiàn)類(后面我們會(huì)講到是ContextIml類)。
3、通過它我們可以獲取應(yīng)用程序的資源和類,也包括一些應(yīng)用級(jí)別操作,例如:?jiǎn)?dòng)一個(gè)Activity,發(fā)送廣播,接受Intent
信息 等。。
于是,我們可以利用該Context對(duì)象去構(gòu)建應(yīng)用級(jí)別操作(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)級(jí)服務(wù)
- public abstract void startActivity(Intent intent); //通過一個(gè)Intent啟動(dòng)Activity
- public abstract ComponentName startService(Intent service); //啟動(dòng)Service
- //根據(jù)文件名得到SharedPreferences對(duì)象
- public abstract SharedPreferences getSharedPreferences(String name,int mode);
- ...
- }
ContextIml.java類 路徑 :/frameworks/base/core/java/android/app/ContextImpl.java
說明:該Context類的實(shí)現(xiàn)類為ContextIml,該類實(shí)現(xiàn)了Context類的功能。請(qǐng)注意,該函數(shù)的大部分功能都是直接調(diào)用
其屬性mPackageInfo去完成,這點(diǎn)我們后面會(huì)講到。
源代碼(部分)如下:
- /**
- * Common implementation of Context API, which provides the base
- * context object for Activity and other application components.
- */
- class ContextImpl extends Context{
- //所有Application程序公用一個(gè)mPackageInfo對(duì)象
- /*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) {
- ...
- //開始啟動(dòng)一個(gè)Activity
- mMainThread.getInstrumentation().execStartActivity(
- getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1);
- }
- }
ContextWrapper類 路徑 :\frameworks\base\core\java\android\content\ContextWrapper.java
說明: 正如其名稱一樣,該類只是對(duì)Context類的一種包裝,該類的構(gòu)造函數(shù)包含了一個(gè)真正的Context引用,即ContextIml
對(duì)象。 源代碼(部分)如下:
- public class ContextWrapper extends Context {
- Context mBase; //該屬性指向一個(gè)ContextIml實(shí)例,一般在創(chuàng)建Application、Service、Activity時(shí)賦值
-
- //創(chuàng)建Application、Service、Activity,會(huì)調(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實(shí)例方法
- }
- }
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 {
- //該屬性指向一個(gè)ContextIml實(shí)例,一般在創(chuàng)建Application、Service、Activity時(shí)賦值
-
- 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子類, 更多信息大家可以自行參考源代碼進(jìn)行理解。
二、 什么時(shí)候創(chuàng)建Context實(shí)例
熟悉了Context的繼承關(guān)系后,我們接下來分析應(yīng)用程序在什么情況需要?jiǎng)?chuàng)建Context對(duì)象的?應(yīng)用程序創(chuàng)建Context實(shí)例的
情況有如下幾種情況:
1、創(chuàng)建Application 對(duì)象時(shí), 而且整個(gè)App共一個(gè)Application對(duì)象
2、創(chuàng)建Service對(duì)象時(shí)
3、創(chuàng)建Activity對(duì)象時(shí)
因此應(yīng)用程序App共有的Context數(shù)目公式為:
總Context實(shí)例個(gè)數(shù) = Service個(gè)數(shù) + Activity個(gè)數(shù) + 1(Application對(duì)應(yīng)的Context實(shí)例)
具體創(chuàng)建Context的時(shí)機(jī)
1、創(chuàng)建Application對(duì)象的時(shí)機(jī)
每個(gè)應(yīng)用程序在第一次啟動(dòng)時(shí),都會(huì)首先創(chuàng)建Application對(duì)象。如果對(duì)應(yīng)用程序啟動(dòng)一個(gè)Activity(startActivity)流程比較
清楚的話,創(chuàng)建Application的時(shí)機(jī)在創(chuàng)建handleBindApplication()方法中,該函數(shù)位于 ActivityThread.java類中 ,如下:
- //創(chuàng)建Application時(shí)同時(shí)創(chuàng)建的ContextIml實(shí)例
- private final void handleBindApplication(AppBindData data){
- ...
- ///創(chuàng)建Application對(duì)象
- 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)建一個(gè)ContextImpl對(duì)象實(shí)例
- appContext.init(this, null, mActivityThread); //初始化該ContextIml實(shí)例的相關(guān)屬性
- ///新建一個(gè)Application對(duì)象
- app = mActivityThread.mInstrumentation.newApplication(
- cl, appClass, appContext);
- appContext.setOuterContext(app); //將該Application實(shí)例傳遞給該ContextImpl實(shí)例
- }
- ...
- }
2、創(chuàng)建Activity對(duì)象的時(shí)機(jī)
通過startActivity()或startActivityForResult()請(qǐng)求啟動(dòng)一個(gè)Activity時(shí),如果系統(tǒng)檢測(cè)需要新建一個(gè)Activity對(duì)象時(shí),就會(huì)
回調(diào)handleLaunchActivity()方法,該方法繼而調(diào)用performLaunchActivity()方法,去創(chuàng)建一個(gè)Activity實(shí)例,并且回調(diào)
onCreate(),onStart()方法等, 函數(shù)都位于 ActivityThread.java類 ,如下:
- //創(chuàng)建一個(gè)Activity實(shí)例時(shí)同時(shí)創(chuàng)建ContextIml實(shí)例
- private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity a = performLaunchActivity(r, customIntent); //啟動(dòng)一個(gè)Activity
- }
- private final Activity performLaunchActivity(ActivityRecord r, Intent customIntent) {
- ...
- Activity activity = null;
- try {
- //創(chuàng)建一個(gè)Activity對(duì)象實(shí)例
- java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
- activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
- }
- if (activity != null) {
- ContextImpl appContext = new ContextImpl(); //創(chuàng)建一個(gè)Activity實(shí)例
- appContext.init(r.packageInfo, r.token, this); //初始化該ContextIml實(shí)例的相關(guān)屬性
- appContext.setOuterContext(activity); //將該Activity信息傳遞給該ContextImpl實(shí)例
- ...
- }
- ...
- }
3、創(chuàng)建Service對(duì)象的時(shí)機(jī)
通過startService或者bindService時(shí),如果系統(tǒng)檢測(cè)到需要新創(chuàng)建一個(gè)Service實(shí)例,就會(huì)回調(diào)handleCreateService()方法,
完成相關(guān)數(shù)據(jù)操作。handleCreateService()函數(shù)位于 ActivityThread.java類,如下:
- //創(chuàng)建一個(gè)Service實(shí)例時(shí)同時(shí)創(chuàng)建ContextIml實(shí)例
- private final void handleCreateService(CreateServiceData data){
- ...
- //創(chuàng)建一個(gè)Service實(shí)例
- 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)建一個(gè)ContextImpl對(duì)象實(shí)例
- context.init(packageInfo, null, this); //初始化該ContextIml實(shí)例的相關(guān)屬性
- //獲得我們之前創(chuàng)建的Application對(duì)象信息
- Application app = packageInfo.makeApplication(false, mInstrumentation);
- //將該Service信息傳遞給該ContextImpl實(shí)例
- context.setOuterContext(service);
- ...
- }
另外,需要強(qiáng)調(diào)一點(diǎn)的是,通過對(duì)ContextImp的分析可知,其方法的大多數(shù)操作都是直接調(diào)用其屬性mPackageInfo(該屬性類
型為PackageInfo)的相關(guān)方法而來。這說明ContextImp是一種輕量級(jí)類,而PackageInfo才是真正重量級(jí)的類。而一個(gè)App里的
所有ContextIml實(shí)例,都對(duì)應(yīng)同一個(gè)packageInfo對(duì)象。
最后給大家分析利用Context獲取SharedPreferences類的使用方法,SharedPreferences類想必大家都使用過,其一般獲取方
法就是通過調(diào)用getSharedPreferences()方法去根據(jù)相關(guān)信息獲取SharedPreferences對(duì)象。具體流程如下:
1 、調(diào)用 getSharedPreferences()獲取對(duì)應(yīng)的的文件,該函數(shù)實(shí)現(xiàn)功能如下:
- //Context類靜態(tài)數(shù)據(jù)集合,以鍵值對(duì)保存了所有讀取該xml文件后所形成的數(shù)據(jù)集合
- private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =
- new HashMap<File, SharedPreferencesImpl>();
-
- @Override
- public SharedPreferences getSharedPreferences(String name, int mode){
- //其所對(duì)應(yīng)的SharedPreferencesImpl對(duì)象 ,該對(duì)象已一個(gè)HashMap集合保存了我們對(duì)該文件序列化結(jié)果
- SharedPreferencesImpl sp;
- File f = getSharedPrefsFile(name); //該包下是否存在對(duì)應(yīng)的文件,不存在就新建一個(gè)
- synchronized (sSharedPrefs) { //是否已經(jīng)讀取過該文件,是就直接返回該SharedPreferences對(duì)象
- sp = sSharedPrefs.get(f);
- if (sp != null && !sp.hasFileChanged()) {
- //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);
- return sp;
- }
- }
- //以下為序列化該xml文件,同時(shí)將數(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) {
- //新建一個(gè)SharedPreferencesImpl對(duì)象,并且設(shè)置其相關(guān)屬性
- sp = new SharedPreferencesImpl(f, mode, map);
- sSharedPrefs.put(f, sp);
- }
- }
- return sp;
- }
- }
2、 SharedPreferences 不過是個(gè)接口,它定義了一些操作xml文件的方法,其真正實(shí)現(xiàn)類為SharedPreferencesImpl ,該類是
ContextIml的內(nèi)部類,該類如下:
- //soga,這種形式我們?cè)诜治鯟ontext ContextIml時(shí)接觸過
- //SharedPreferences只是一種接口,其真正實(shí)現(xiàn)類是SharedPreferencesImpl類
- private static final class SharedPreferencesImpl implements SharedPreferences{
- private Map mMap; //保存了該文件序列化結(jié)果后的操作, 鍵值對(duì)形式
-
- //通過key值獲取對(duì)應(yīng)的value值
- public String getString(String key, String defValue) {
- synchronized (this) {
- String v = (String)mMap.get(key);
- return v != null ? v : defValue;
- }
- }
- ...
- //獲得該SharedPreferencesImpl對(duì)象對(duì)應(yīng)的Edito類,對(duì)數(shù)據(jù)進(jìn)行操作
- public final class EditorImpl implements Editor {
- private final Map<String, Object> mModified = Maps.newHashMap(); //保存了對(duì)鍵值變化的集合
- }
- }
基本上獲取SharedPreferences 對(duì)象就是這么來的,關(guān)于Context里的更多方法請(qǐng)大家參照源代碼認(rèn)真學(xué)習(xí)吧。