理解Activity的创建过程

2019-10-25  本文已影响0人  only_run

笔者水平有限 ,涉及的源码只是部分摘取,只是流程方面的理解,忽略了不少具体细节,本篇文章只做记录之用。

首先需要了解以下几个概念

Android中抽象的入口函数式 ActivityThread的main函数

//ActivityThread
public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ...
        ActivityThread thread = new ActivityThread();  //1
        thread.attach(false, startSeq); //2
        ...
        Looper.loop();
    
}

注释1 创建了ActivityThread对象 可以理解为Android中的一个线程(并不是只是类似)
注释2 thread通过binder机制 发送消息给AMS
继续看attach方法

private void attach(boolean system, long startSeq) {
        ...
        if (!system) {
            ...
            final IActivityManager mgr = ActivityManager.getService();  //1
            try {
                mgr.attachApplication(mAppThread, startSeq);  //2
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            ...
        }
        ...
}

重点来了 注释1 获取AMS的 AIDLD的代理对象 注释2发送信息给AMS
接着调用 ActivityManagerService类的 attachApplication方法->attachApplicationLocked方法

//ActivityManagerService
private final boolean attachApplicationLocked(IApplicationThread thread,
                                                  int pid, int callingUid, long startSeq) {
       ...
        if (app.instr != null) {
           thread.bindApplication(processName, appInfo, providers, app.instr.mClass,
                    profilerInfo, app.instr.mArguments, app.instr.mWatcher, app.instr.mUiAutomationConnection,
                    testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation,
                    isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(getGlobalConfiguration()),
                    app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(),
                    buildSerial, isAutofillCompatEnabled);   //1
        } else {
          
            thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
                    null, null, null, testMode, mBinderTransactionTrackingEnabled,
                    enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent,
                    new Configuration(getGlobalConfiguration()), app.compat, getCommonServicesLocked(app.isolated),
                    mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, isAutofillCompatEnabled);  //2
        }
        ...
       
        if (mStackSupervisor.attachApplicationLocked(app)) { //3
            didSomething = true;
        }
        ...
}

注释1 进程连接application建立关系,注释2也是 但是有区别的注释1在当前进程正在活动条件下才执行,但都会通过binder机制发送消息给应用进程

//ActivityThread.ApplicationThread
public final void bindApplication(String processName...boolean autofillCompatibilityEnabled) {
        ...
        //最后使用Handler发送消息,并携带数据
        //通过handel切换到应用的主线程 创建application,并调用onCreate方法(这里跳过android系统源码具体的细节了)
        sendMessage(H.BIND_APPLICATION, data);
}
 //调用 顺序ActivityThread.H.handleMessage->ActivityThread.handleBindApplication
//ActivityThread 
private void handleBindApplication(AppBindData data) {
        ...
        final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);  
        ...
        Application app;
        ...
        //创建Application
        app = data.info.makeApplication(data.restrictedBackupMode, null);  
        ...
        //调用Application中的onCreate方法
        mInstrumentation.callApplicationOnCreate(app);  
        ...
}

注释3 如果Activity不存在就创建Activity 通过binder机制发送信息 给应用进程的binder服务端 ActivityThread.ApplicationThread
注释3 attachApplicationLocked方法之后的调用顺序:ActivityStackSupervisor.realStartActivityLocked->ClientLifecycleManager.scheduleTransaction->ActivityThread.ApplicationTread.scheduleTransaction

##ActivityThread.ApplicationTread
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        //ActivityThread.this 指的是父类ClientTransactionHandler
        ActivityThread.this.scheduleTransaction(transaction);
}

//ClientTransactionHandler
void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        //发送Handler消息
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//调用TransactionExecutor.execute->TransactionExecutor.executeCallbacks
//...此处有跳过,没有啃透 参考了大牛的描述
//最后调用
//ActivityThread
public Activity handleLaunchActivity(ActivityClientRecord r,
                                         PendingTransactionActions pendingActions, Intent customIntent) {
        ...
        final Activity a = performLaunchActivity(r, customIntent);   
        ...
        return a;
}
//ActivityThread
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        ContextImpl appContext = createBaseContextForActivity(r);   
        Activity activity = null;
        try {
//获取classLoader使用反射创建Activity
            java.lang.ClassLoader cl = appContext.getClassLoader();   
            activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);  
           ...
        } catch (Exception e) {
           ...
        }
        ...
        //调用Activity onCreate方法
        if (r.isPersistable()) {
            mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);   
        } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);   
        }
        ...
        return activity;
}

上一篇下一篇

猜你喜欢

热点阅读