首次启动App,Application里的onCreate方法是如何被调用到的?

我们知道onCreate是Application的第一个生命周期,但是为什么它是第一个呢,它是怎么被触发调用的?这里就对这个问题进行研究:

 从上图来看,app进程会由zygote进程fork出来后,走到ActivityThread,ActivityThread里有一个main()方法,这里就是app进程的起点:

//ActivityThread.java
public static void main(String[] args) {
    ......
    //省略一部分代码

    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

     ......
    //省略一部分代码

}

在main()方法中,里面会new 一个ActivityThread后,调用它的attach()方法:

//ActivityThread.java
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
    //省略一部分代码

    //是在进行AMS跨进程的binder通信
    final IActivityManager mgr = ActivityManager.getService();
    try {
          mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
          throw ex.rethrowFromSystemServer();
        }

     ......
    //省略一部分代码
    
}

 ActivityManager.getService(),通过源码知道它拿到的是一个ActivityManagerService实例:

//ActivityManager.java
@UnsupportedAppUsage
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
//ActivityManager.java
@UnsupportedAppUsage
    private static final Singleton<IActivityManager> IActivityManagerSingleton =
            new Singleton<IActivityManager>() {
                @Override
                protected IActivityManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
                }
            };

回来继续看attach()方法,mgr主要负责跟AMS通信后,调用了mgr.attachApplication(mAppThread,startSeq)方法,还顺便传了mAppThread过去:

//ActivityThread.java
@UnsupportedAppUsage
final ApplicationThread mAppThread = new ApplicationThread();


//通信类,专门负责ActivityThread和AMS之间的通信
//ActivityThread这边准备了N个回调函数给AMS调用
 private class ApplicationThread extends IApplicationThread.Stub {

    .............

}

现在我们知道mgr.attachApplication(),其实是调用ActivityManagerService.attachApplication()方法:

//ActivityManagerService.java
@Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        if (thread == null) {
            throw new SecurityException("Invalid application interface");
        }
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

接着继续调attachApplicationLocked(thread, callingPid, callingUid, startSeq);

//ActivityManagerService.java
@GuardedBy("this")
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
            int pid, int callingUid, long startSeq) {

    //进程数据,PMS将每个app的清单文件解析后,AMS只要去找PMS直接get过来,
    //就可以生成这个进程数据
    ProcessRecord app;

...............
//这里的thread就是ActivityThread那里的  ApplicationThread
    thread.bindApplication(processName, appInfo, providerList,
           instr2.mClass,
           profilerInfo, instr2.mArguments,
           instr2.mWatcher,
           instr2.mUiAutomationConnection, testMode,
           mBinderTransactionTrackingEnabled, enableTrackAllocation,
           isRestrictedBackupMode || !normalMode, app.isPersistent(),
           new Configuration(app.getWindowProcessController().getConfiguration()),
           app.compat, getCommonServicesLocked(app.isolated),
           mCoreSettingsObserver.getCoreSettingsLocked(),
           buildSerial, autofillOptions, contentCaptureOptions,
           app.mDisabledCompatChanges);
    

}

bindApplication方法里的参数,是application的相关的信息,这些信息是AMS去PMS那里拿过来的,回调给了ActivityThread:

//ActivityThread
@Override
        public final void bindApplication(String processName, ApplicationInfo appInfo,
                ProviderInfoList providerList, ComponentName instrumentationName,
                ProfilerInfo profilerInfo, Bundle instrumentationArgs,
                IInstrumentationWatcher instrumentationWatcher,
                IUiAutomationConnection instrumentationUiConnection, int debugMode,
                boolean enableBinderTracking, boolean trackAllocation,
                boolean isRestrictedBackupMode, boolean persistent, Configuration config,
                CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
                String buildSerial, AutofillOptions autofillOptions,
                ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) 

{
    ......
//从AMS回调回来的相关信息,组成一个AppBindData
    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providerList.getList();
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
   
         .......

    sendMessage(H.BIND_APPLICATION, data);

}

从AMS回调回来的相关信息,组成一个AppBindData后,发一个message,sendMessage(H.BIND_APPLICATION, data);这里的H是ActivityThread自己维护的一个Handler

//ActivityThread
class H extends Handler {
    public static final int BIND_APPLICATION        = 110;
    ......

   switch (msg.what) {
       case BIND_APPLICATION:
       Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
       AppBindData data = (AppBindData)msg.obj;
       handleBindApplication(data);
       Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
       break; 

......

}

看下这个BIND_APPLICATION,调用了handleBindApplication(data):

//ActivityThread
@UnsupportedAppUsage
private void handleBindApplication(AppBindData data) {

    ......

//这里构建一个Instrumentation ->它专门负责Application和Activity的相关活动处理
//比如:new 、 生命周期相关调用
    try {
         final ClassLoader cl = instrContext.getClassLoader();
         mInstrumentation = (Instrumentation)
         cl.loadClass(data.instrumentationName.getClassName()).newInstance();
            } catch (Exception e) {
         throw new RuntimeException(
        "Unable to instantiate instrumentation "
           + data.instrumentationName + ": " + e.toString(), e);
            }

......

Application app;
        final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
        final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
        try {
        //这里开始对application进行构建
        app = data.info.makeApplication(data.restrictedBackupMode, null);
......
    
}

看下makeApplicaiton()方法:

//LoadedApk.java
public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {

    ......
//在这里可以知道,通过调用  mInstrumentation的newApplication()方法,
    app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);


.....

 if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }
......

}

看这个instrumentation.callApplicationOnCreate(app):

//Instrumentation.java
public void callApplicationOnCreate(Application app) {
        app.onCreate();
    }

在这里就调用了app的onCreate方法。


做个总结:

  1. zygote进程fork app进程之后,系统启动ActivityThred
  2. ActivityThread准备一个ApplicationThread类(用于去和AMS进行通信)
  3. ActivityThread发起一个对于AMS.attachApplication的binder调用
  4. 在AMS中验证ActivityThread的调用过程
  5. 忽略其他不看,关于流程重点在bindApplication上
  6. 回到bindApplication中发现数据组装后的Handler调用
  7. sendMessage消息转入handlerMessage中(最终调用到handleBindApplication)
  8. handleBindApplication(
    1. mInstrumentation生命周期管理对象的构建
    2. Application的创建(反射构建Application信息、调用oncreate函数))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值