`
dawuafang
  • 浏览: 1105172 次
文章分类
社区版块
存档分类
最新评论

Android中Context详解——你所不知道的Context

 
阅读更多

出处 :http://blog.csdn.net/qinjuning

大家好, 今天给大家介绍下我们在应用开发中最熟悉而陌生的朋友-----Context类 ,说它熟悉,是应为我们在开发中时刻的在与它打交道,例如:Service、BroadcastReceiver、Activity等都会利用到Context的相关方法 ; 说它陌生,完全是因为我们真正的不懂Context的原理、类结构关系。

Context,中文直译为“上下文”,SDK中对其说明如下:Interface to global information about an application environment. This is an abstract class whose implementationis provided by the Android system. It allows access to application-specific resources and classes, as well as up-callsfor 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相关类的继承关系

相关类介绍:

Context类 路径: /frameworks/base/core/java/android/content/Context.java

说明: 抽象类,提供了一组通用的API。

源代码(部分)如下:

  1. publicabstractclassContext{
  2. ...
  3. publicabstractObjectgetSystemService(Stringname);//获得系统级服务
  4. publicabstractvoidstartActivity(Intentintent);//通过一个Intent启动Activity
  5. publicabstractComponentNamestartService(Intentservice);//启动Service
  6. //根据文件名得到SharedPreferences对象
  7. publicabstractSharedPreferencesgetSharedPreferences(Stringname,intmode);
  8. ...
  9. }

ContextIml.java类 路径 :/frameworks/base/core/java/android/app/ContextImpl.java

说明:该Context类的实现类为ContextIml,该类实现了Context类的功能。请注意,该函数的大部分功能都是直接调用其属性mPackageInfo去完成,这点我们后面会讲到。

源代码(部分)如下:

  1. /**
  2. *CommonimplementationofContextAPI,whichprovidesthebase
  3. *contextobjectforActivityandotherapplicationcomponents.
  4. */
  5. classContextImplextendsContext{
  6. //所有Application程序公用一个mPackageInfo对象
  7. /*package*/ActivityThread.PackageInfomPackageInfo;
  8. @Override
  9. publicObjectgetSystemService(Stringname){
  10. ...
  11. elseif(ACTIVITY_SERVICE.equals(name)){
  12. returngetActivityManager();
  13. }
  14. elseif(INPUT_METHOD_SERVICE.equals(name)){
  15. returnInputMethodManager.getInstance(this);
  16. }
  17. }
  18. @Override
  19. publicvoidstartActivity(Intentintent){
  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. publicclassContextWrapperextendsContext{
  2. ContextmBase;//该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
  3. //创建Application、Service、Activity,会调用该方法给mBase属性赋值
  4. protectedvoidattachBaseContext(Contextbase){
  5. if(mBase!=null){
  6. thrownewIllegalStateException("Basecontextalreadyset");
  7. }
  8. mBase=base;
  9. }
  10. @Override
  11. publicvoidstartActivity(Intentintent){
  12. mBase.startActivity(intent);//调用mBase实例方法
  13. }
  14. }


ContextThemeWrapper类路径:/frameworks/base/core/java/android/view/ContextThemeWrapper.java

说明:该类内部包含了主题(Theme)相关的接口,即android:theme属性指定的。只有Activity需要主题,Service不需要主题,所以Service直接继承于ContextWrapper类。

源代码(部分)如下:

  1. publicclassContextThemeWrapperextendsContextWrapper{
  2. //该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
  3. privateContextmBase;
  4. //mBase赋值方式同样有一下两种
  5. publicContextThemeWrapper(Contextbase,intthemeres){
  6. super(base);
  7. mBase=base;
  8. mThemeResource=themeres;
  9. }
  10. @Override
  11. protectedvoidattachBaseContext(ContextnewBase){
  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. privatefinalvoidhandleBindApplication(AppBindDatadata){
  3. ...
  4. ///创建Application对象
  5. Applicationapp=data.info.makeApplication(data.restrictedBackupMode,null);
  6. ...
  7. }
  8. publicApplicationmakeApplication(booleanforceDefaultAppClass,Instrumentationinstrumentation){
  9. ...
  10. try{
  11. java.lang.ClassLoadercl=getClassLoader();
  12. ContextImplappContext=newContextImpl();//创建一个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. privatefinalvoidhandleLaunchActivity(ActivityRecordr,IntentcustomIntent){
  3. ...
  4. Activitya=performLaunchActivity(r,customIntent);//启动一个Activity
  5. }
  6. privatefinalActivityperformLaunchActivity(ActivityRecordr,IntentcustomIntent){
  7. ...
  8. Activityactivity=null;
  9. try{
  10. //创建一个Activity对象实例
  11. java.lang.ClassLoadercl=r.packageInfo.getClassLoader();
  12. activity=mInstrumentation.newActivity(cl,component.getClassName(),r.intent);
  13. }
  14. if(activity!=null){
  15. ContextImplappContext=newContextImpl();//创建一个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. privatefinalvoidhandleCreateService(CreateServiceDatadata){
  3. ...
  4. //创建一个Service实例
  5. Serviceservice=null;
  6. try{
  7. java.lang.ClassLoadercl=packageInfo.getClassLoader();
  8. service=(Service)cl.loadClass(data.info.name).newInstance();
  9. }catch(Exceptione){
  10. }
  11. ...
  12. ContextImplcontext=newContextImpl();//创建一个ContextImpl对象实例
  13. context.init(packageInfo,null,this);//初始化该ContextIml实例的相关属性
  14. //获得我们之前创建的Application对象信息
  15. Applicationapp=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. privatestaticfinalHashMap<File,SharedPreferencesImpl>sSharedPrefs=
  3. newHashMap<File,SharedPreferencesImpl>();
  4. @Override
  5. publicSharedPreferencesgetSharedPreferences(Stringname,intmode){
  6. //其所对应的SharedPreferencesImpl对象,该对象已一个HashMap集合保存了我们对该文件序列化结果
  7. SharedPreferencesImplsp;
  8. Filef=getSharedPrefsFile(name);//该包下是否存在对应的文件,不存在就新建一个
  9. synchronized(sSharedPrefs){//是否已经读取过该文件,是就直接返回该SharedPreferences对象
  10. sp=sSharedPrefs.get(f);
  11. if(sp!=null&&!sp.hasFileChanged()){
  12. //Log.i(TAG,"Returningexistingprefs"+name+":"+sp);
  13. returnsp;
  14. }
  15. }
  16. //以下为序列化该xml文件,同时将数据写到map集合中
  17. Mapmap=null;
  18. if(f.exists()&&f.canRead()){
  19. try{
  20. str=newFileInputStream(f);
  21. map=XmlUtils.readMapXml(str);
  22. str.close();
  23. }
  24. ...
  25. }
  26. synchronized(sSharedPrefs){
  27. if(sp!=null){
  28. //Log.i(TAG,"Updatingexistingprefs"+name+""+sp+":"+map);
  29. sp.replace(map);//更新数据集合
  30. }else{
  31. sp=sSharedPrefs.get(f);
  32. if(sp==null){
  33. //新建一个SharedPreferencesImpl对象,并且设置其相关属性
  34. sp=newSharedPreferencesImpl(f,mode,map);
  35. sSharedPrefs.put(f,sp);
  36. }
  37. }
  38. returnsp;
  39. }
  40. }

2、 SharedPreferences 不过是个接口,它定义了一些操作xml文件的方法,其真正实现类为SharedPreferencesImpl ,该类是ContextIml的内部类,该类如下:

  1. //soga,这种形式我们在分析ContextContextIml时接触过
  2. //SharedPreferences只是一种接口,其真正实现类是SharedPreferencesImpl类
  3. privatestaticfinalclassSharedPreferencesImplimplementsSharedPreferences{
  4. privateMapmMap;//保存了该文件序列化结果后的操作,键值对形式
  5. //通过key值获取对应的value值
  6. publicStringgetString(Stringkey,StringdefValue){
  7. synchronized(this){
  8. Stringv=(String)mMap.get(key);
  9. returnv!=null?v:defValue;
  10. }
  11. }
  12. ...
  13. //获得该SharedPreferencesImpl对象对应的Edito类,对数据进行操作
  14. publicfinalclassEditorImplimplementsEditor{
  15. privatefinalMap<String,Object>mModified=Maps.newHashMap();//保存了对键值变化的集合
  16. }
  17. }


基本上获取SharedPreferences 对象就是这么来的,关于Context里的更多方法请大家参照源代码认真学习吧。

<wbr></wbr>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics