Context的子类实现:ContextImpl的初始化

一、Context

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、它描述的是一个应用程序环境的信息,即上下文。

2、该类是一个抽象(abstract class)类,Android提供了该抽象类的具体实现类(后面我们会讲到是ContextIml)

3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别操作,例如:启动一个Activity,发送广播,接受Intent

信息 等。。

对于我们用到的ActivityServiceApplication等都是ContextContext是一个抽象类,它的真正实现是ContextImpl.java中,而ActivityServiceApplication用到的Context都是ContextImpl的实例。

二、Context实例创建:

1、创建Activity时:

在启动Activity时:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

Activity activity = null;

if (activity != null) {

      ContextImpl appContext = new ContextImpl();

      appContext.init(r.packageInfo, r.token, this);

      appContext.setOuterContext(activity);

        activity.attach(appContext, this, getInstrumentation(), r.token,

             r.ident, app, r.intent, r.activityInfo, title, r.parent,

             r.embeddedID, r.lastNonConfigurationInstances, config);

}

        }

2.Service:

ActivityThread.java中,当创建handleCreateService进行初始化:

Service service = null;

try {

ContextImpl context = new ContextImpl();

context.init(packageInfo, null, this);

Application app = packageInfo.makeApplication(false, mInstrumentation);

context.setOuterContext(service);

service.attach(context, this, data.info.name, data.token, app,

ActivityManagerNative.getDefault());

service.onCreate();

}

3.Application

private final void handleBindApplication(AppBindData data){
     ...
    ///创建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();    //创建一个ContextImpl对象实例
         appContext.init(this, null, mActivityThread);  //初始化该ContextIml实例的相关属性
         ///新建一个Application对象 
         app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
        appContext.setOuterContext(app);  //将该Application实例传递给该ContextImpl实例         
    }

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值