zoukankan      html  css  js  c++  java
  • Android中的Context

    一. 与Context相联系的类的继承关系如下图:

      

      Context为抽象类,提供了一组通用的API。它的实现类为ContextImpl,该类实现了Context的功能,其大部分功能都是直接调用其属性mPackageInfo完成。

      ContextWrapper类是对Context类的一种包装,该类的构造函数包含了一个真正的Context引用,即ContextImpl对象。源代码如下:

     

     1 public class ContextWrapper extends Context{
     2     Context mbase;//该属性指向一个ContextIml实例,一般在创建Application、Service、Activity时赋值
     3     //创建Application、Service、Activity,会调用该方法给mBase属性赋值
     4     protected void attachBaseContext(Context base){
     5         if(mBase!=null){
     6             throw new IllegalStateException("Base context already set");
     7         }
     8         mbase=base;
     9         }
    10         @Override
    11         public void startActivity(Intent intent){
    12             mBase.startActivity(intent);//调用mBase实例方法
    13         }
    14 }

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

        Activity类,Service类,Application类都是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 private final void 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 instrumenttation){
     9     ......
    10     try{
    11         java.lang.ClassLoader cl=getClassLoader();
    12         ContextImpl appContext=new ContextImpl();//创建一个ContextIml实例对象
    13         appContext.init(this,null,mActivityThread);//初始化该ContextIml实例的相关属性
    14         //新建一个Application对象
    15         app=mActivityThread.mInstrumentation.newApplication(cl,appClass,appContext);
    16 appContext.setOuterContext(app);//将该Application实例传递给该ContextIml实例
    17 }
    18 ....

      2.创建Activity对象的时机

        通过startActivity()或startActivityForResult()请求启动一个Activity时,如果系统检测需要新建一个Activity对象时,就会回调handleLaunchActivity()方法,该方法继而调用performLaunchActivity()方法,去创建一个Activity实例,并且回调onCreate(),onStart()方法等,函数都位于ActivityThread.java类

     1     //创建一个Activity实例时同时创建ContextIml实例  
     2     private final void handleLaunchActivity(ActivityRecord r, Intent customIntent) {  
     3         ...  
     4         Activity a = performLaunchActivity(r, customIntent);  //启动一个Activity  
     5     }  
     6     private final 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     private final void 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     }  

      通过对ContextImpl的分析可知,其方法的大多数操作都是直接调用其属性mPackageInfo(该属性类型为PackageInfo)的相关方法而来。这说明ContextImpl是一种轻量级的类,而PackageInfo才是真正重量级的类。而一个App里的所有ContextImpl实例,都对应同一个packageInfo对象。

      最后分析利用Context获取SharedPreferences类,一般的获取方法就是通过getSharedPreference()方法根据相关信息获取SharedPreference对象。

    具体如下:

      1.调用getSharedPreferences()获取对应的文件,该函数实现功能如下:

     1     //Context类静态数据集合,以键值对保存了所有读取该xml文件后所形成的数据集合  
     2     private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =   
     3            new HashMap<File, SharedPreferencesImpl>();   
     4       
     5     @Override  
     6     public SharedPreferences getSharedPreferences(String name, int mode){  
     7          //其所对应的SharedPreferencesImpl对象 ,该对象已一个HashMap集合保存了我们对该文件序列化结果  
     8          SharedPreferencesImpl sp;    
     9          File f = getSharedPrefsFile(name);  //该包下是否存在对应的文件,不存在就新建一个  
    10          synchronized (sSharedPrefs) {       //是否已经读取过该文件,是就直接返回该SharedPreferences对象  
    11              sp = sSharedPrefs.get(f);  
    12              if (sp != null && !sp.hasFileChanged()) {  
    13                  //Log.i(TAG, "Returning existing prefs " + name + ": " + sp);  
    14                  return sp;  
    15              }  
    16          }  
    17          //以下为序列化该xml文件,同时将数据写到map集合中       
    18          Map map = null;  
    19          if (f.exists() && f.canRead()) {  
    20              try {  
    21                  str = new FileInputStream(f);  
    22                  map = XmlUtils.readMapXml(str);  
    23                  str.close();  
    24              }   
    25              ...  
    26          }  
    27            
    28          synchronized (sSharedPrefs) {  
    29              if (sp != null) {  
    30                  //Log.i(TAG, "Updating existing prefs " + name + " " + sp + ": " + map);  
    31                  sp.replace(map);   //更新数据集合  
    32              } else {  
    33                  sp = sSharedPrefs.get(f);  
    34                  if (sp == null) {    
    35                      //新建一个SharedPreferencesImpl对象,并且设置其相关属性  
    36                      sp = new SharedPreferencesImpl(f, mode, map);    
    37                      sSharedPrefs.put(f, sp);  
    38                  }  
    39              }  
    40              return sp;  
    41          }  
    42     }  

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

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

      以上内容转自:http://blog.csdn.net/qinjuning/article/details/7310620#

  • 相关阅读:
    PHP多台服务器跨域SESSION共享
    php发送post请求到nodejs服务器
    xampp使用phpunit
    MarkdownPad 2
    php安装memcache注意事项
    yii 基础版用rbac-plus
    yii2高级版账号密码问题
    yii2 rbac-plus的使用
    manjaro-VM虚拟机vmmon错误
    Java并发包中的线程池ThreadPoolExecutor
  • 原文地址:https://www.cnblogs.com/dazuihou/p/3612485.html
Copyright © 2011-2022 走看看