022android初级篇之android的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. 它提供了application 环境全局信息接口;
  2. 该类是一个抽象类(abstract class),Android提供了该抽象类的具体实现类;
  3. 通过该类我们可以访问应用程序的资源和类,也包括进行应用级别的操作,例如启动一个Activity,发生Broadcast,接收Intent信息等。

相关的类

022android初级篇之android的Context_第1张图片
022_01.png

Context类

路径: /frameworks/base/core/java/android/content/Context.java
说明: 抽象类,提供了一组通用的API。

public static final int MODE_PRIVATE = 0x0000;
public static final int MODE_APPEND = 0x8000;

public static final int MODE_MULTI_PROCESS = 0x0004;

 /** Return an AssetManager instance for your application's package. */
public abstract AssetManager getAssets();

/** Return a Resources instance for your application's package. */
public abstract Resources getResources();

/** Return PackageManager instance to find global package information. */
public abstract PackageManager getPackageManager();

/** Return a ContentResolver instance for your application's package. */
public abstract ContentResolver getContentResolver();
public abstract Looper getMainLooper();
 public abstract Context getApplicationContext();

ContextIml.java类

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

说明:该Context类的实现类为ContextIml,该类实现了Context类的功能。该函数的大部分功能都是直接调用其属性mPackageInfo去完成。

ContextWrapper类

路径 :\frameworks\base\core\java\android\content\ContextWrapper.java

说明: 正如其名称一样,该类只是对Context类的一种包装,该类的构造函数包含了一个真正的Context引用,即ContextIml对象。

ContextThemeWrapper类

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

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

Activity类 、Service类 、Application类都是Context的子类

创建Context实例

因此应用程序App共有的Context数目公式为:

总Context实例个数 = Service个数 + Activity个数 + 1(Application对应的Context实例)

1、创建Application对象的时机

每个应用程序在第一次启动时,都会首先创建Application对象。如果对应用程序启动一个Activity(startActivity)流程比较
清楚的话,创建Application的时机在创建handleBindApplication()方法中,该函数位于 ActivityThread.java类中

2、创建Activity对象的时机

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

3、创建Service对象的时机

通过startService或者bindService时,如果系统检测到需要新创建一个Service实例,就会回调handleCreateService()方法,
完成相关数据操作。handleCreateService()函数位于 ActivityThread.java类

参考链接

  1. Android中Context详解 ---- 你所不知道的Context
  2. Android源码分析-全面理解Context

你可能感兴趣的:(022android初级篇之android的Context)