美文网首页
Android启动流程

Android启动流程

作者: jxiang112 | 来源:发表于2022-04-04 13:22 被阅读0次

    1、Actvity

    Activity的startActivity是一个重载函数,所有的startActivity重载函数最终都会调用startActivityForResult:

    @Override
        public void startActivity(Intent intent, @Nullable Bundle options) {
            if (options != null) {
                startActivityForResult(intent, -1, options);
            } else {
                // Note we want to go through this call for compatibility with
                // applications that may have overridden the method.
                startActivityForResult(intent, -1);
            }
        }
    

    startActivityForResult调用Instrumentation的execStartActivity:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
           //.......
                Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                        this, mMainThread.getApplicationThread(), mToken, this,
                        intent, requestCode, options);
       //.......
    }
    

    2、Instrumentation

    execStartActivity中使用ActivityManager.getService获取ActvityManagerService(简称AMS)远端代理,再通过代理调用远端接口startActivityAsUser:

    public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, String resultWho,
                Intent intent, int requestCode, Bundle options, UserHandle user) {
      //......
      try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                int result = ActivityManager.getService()
                    .startActivityAsUser(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, resultWho,
                            requestCode, 0, null, options, user.getIdentifier());
                checkStartActivityResult(result, intent);
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
            return null;
      //......
    }
    

    3、ActivityManager

    上一步中getService是通过SystemService来获取AMS的代理的:

    public static IActivityManager getService() {
            return IActivityManagerSingleton.get();
        }
    
        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;
                    }
                };
    

    这里是进行了进程间通信,ServiceManager.getService从ServiceManager进程中获取AMS提供的服务Binder, 接下来使用AMS的调用也是进行的进程间通信。

    4、IActivityManager.Stub

    IActivityManager是aidl接口编译之后生成的类,它是AMS抽象的接口,内部有Stub类和Proxy类,其中Stub类是AMS的服务桩类,负责onTransact解析、处理、响应Client的请求,Proxy是供Client端调用远端AMS提供的服务:

    public interface IActivityManager extends IInterface {
      public abstract static class Stub extends Binder implements IActivityManager {
            private static final String DESCRIPTOR = "android.app.IActivityManager";
            //......
            //启动activity的code
            static final int TRANSACTION_startActivity = 3;
            //......
            //将AMS封装在Proxy中,供Client调用Proxy代理的AMS接口
            public static IActivityManager asInterface(IBinder obj) {
                if (obj == null) {
                    return null;
                } else {
                    IInterface iin = obj.queryLocalInterface("android.app.IActivityManager");
                    return (IActivityManager)(iin != null && iin instanceof IActivityManager ? (IActivityManager)iin : new IActivityManager.Stub.Proxy(obj));
                }
            }
            //AMS
            public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
                switch(code) {
                    //......
                    case 3: //启动activity的code
                    //从data中解析启动Activity的参数信息
                    data.enforceInterface("android.app.IActivityManager");
                    _arg0 = android.app.IApplicationThread.Stub.asInterface(data.readStrongBinder());
                    _arg1 = data.readString();
                    if (0 != data.readInt()) {
                        _arg2 = (Intent)Intent.CREATOR.createFromParcel(data);
                    } else {
                        _arg2 = null;
                    }
    
                    _arg3 = data.readString();
                    _arg4 = data.readStrongBinder();
                    _arg5 = data.readString();
                    _arg6 = data.readInt();
                    _arg7 = data.readInt();
                    if (0 != data.readInt()) {
                        _arg8 = (ProfilerInfo)ProfilerInfo.CREATOR.createFromParcel(data);
                    } else {
                        _arg8 = null;
                    }
    
                    if (0 != data.readInt()) {
                        _arg9 = (Bundle)Bundle.CREATOR.createFromParcel(data);
                    } else {
                        _arg9 = null;
                    }
                    //调用AMS的startActivity
                    _arg10 = this.startActivity(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5, _arg6, _arg7, _arg8, _arg9);
                    //启动Activity的响应
                    reply.writeNoException();
                    reply.writeInt(_arg10);
                    return true;
                }
            }
           //......
          //AMS的代理类,实现AMS提供的所有接口,其使用AMS提供的Binder远程调用AMS提供的接口
          private static class Proxy implements IActivityManager {
                private IBinder mRemote;
    
                Proxy(IBinder remote) {
                    this.mRemote = remote;
                }
    
                public IBinder asBinder() {
                    return this.mRemote;
                }
                //......
                //供Client调用远程AMS提供的接口startActivity启动Activity
                public int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
                    Parcel _data = Parcel.obtain();
                    Parcel _reply = Parcel.obtain();
    
                    int _result;
                    try {
                        //将启动Activity的参数写入data中
                        _data.writeInterfaceToken("android.app.IActivityManager");
                        _data.writeStrongBinder(caller != null ? caller.asBinder() : null);
                        _data.writeString(callingPackage);
                        if (intent != null) {
                            _data.writeInt(1);
                            intent.writeToParcel(_data, 0);
                        } else {
                            _data.writeInt(0);
                        }
    
                        _data.writeString(resolvedType);
                        _data.writeStrongBinder(resultTo);
                        _data.writeString(resultWho);
                        _data.writeInt(requestCode);
                        _data.writeInt(flags);
                        if (profilerInfo != null) {
                            _data.writeInt(1);
                            profilerInfo.writeToParcel(_data, 0);
                        } else {
                            _data.writeInt(0);
                        }
    
                        if (options != null) {
                            _data.writeInt(1);
                            options.writeToParcel(_data, 0);
                        } else {
                            _data.writeInt(0);
                        }
                        //调用AMS提供的Binder启动Activity,code为3
                        this.mRemote.transact(3, _data, _reply, 0);
                        _reply.readException();
                        _result = _reply.readInt();
                    } finally {
                        _reply.recycle();
                        _data.recycle();
                    }
    
                    return _result;
                }
          }
      }
    }
    

    结合3、4的源码,先是通过ServiceManager获取AMS提供的Binder的代理IActivityManager.Stub.Proxy,通过代理远程调用AMS提供的接口startActivity,其内部是调用AMS 提供Binder(即IActivityManager.Stub)的transact进行进程间通信,接着经过binder驱动将启动activity的指令及数据传递到AMS的Stub中,在Stub的onTransact中解析出启动activity的参数,再调用AMS的startActivity。

    5、ActivityManagerService(简称AMS)

    AMS的startActivity最终进入startActivityAsUser,startActivityAsUser通过ActivityStartController代理构建ActivityStarter及启动activity参数,最后使用构建出的ActivityStarter执行execute方法:

        @Override
        public final int startActivity(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions,
                    UserHandle.getCallingUserId());
        }
        public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
                Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
                int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
                boolean validateIncomingUser) {
            enforceNotIsolatedCaller("startActivity");
    
            userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                    Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    
            // TODO: Switch to user app stacks here.
            return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                    .setCaller(caller)
                    .setCallingPackage(callingPackage)
                    .setResolvedType(resolvedType)
                    .setResultTo(resultTo)
                    .setResultWho(resultWho)
                    .setRequestCode(requestCode)
                    .setStartFlags(startFlags)
                    .setProfilerInfo(profilerInfo)
                    .setActivityOptions(bOptions)
                    .setMayWait(userId)
                    .execute();
    
        }
    

    6、ActivityStarter

    ActivityStarter用于解析如何启动Activity。它记录了Activity的所有逻辑,用于确定如何将意图Intent和标志Flag转为Activity以及关联的任务和堆栈。
    因为步骤5中设置了mayWait=true,所有ActivityStarter的execute执行startActivityMayWait:

    int execute() {
            try {
                // TODO(b/64750076): Look into passing request directly to these methods to allow
                // for transactional diffs and preprocessing.
                if (mRequest.mayWait) {
                    return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                            mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                            mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                            mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                            mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup);
                } else {
                    return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                            mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                            mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                            mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                            mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                            mRequest.outActivity, mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup);
                }
            } finally {
                onExecutionComplete();
            }
        }
    

    startActivityMayWait又调用startActivity:

    private int startActivityMayWait(IApplicationThread caller, int callingUid,
                String callingPackage, Intent intent, String resolvedType,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode, int startFlags,
                ProfilerInfo profilerInfo, WaitResult outResult,
                Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
                int userId, TaskRecord inTask, String reason,
                boolean allowPendingRemoteAnimationRegistryLookup) {
        //......
        int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                        voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                        callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                        ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                        allowPendingRemoteAnimationRegistryLookup);
        //.......
    }
    

    startActivity又调用startActivity重载方法:

    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
                String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
                String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
                SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
                ActivityRecord[] outActivity, TaskRecord inTask, String reason,
                boolean allowPendingRemoteAnimationRegistryLookup) {
    
            //......
            mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                    callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                    inTask, allowPendingRemoteAnimationRegistryLookup);
    
           //......
        }
    

    还是调用startActivity重载方法:

    private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
                String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
                String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
                SafeActivityOptions options,
                boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
                TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
        //......
        return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                    true /* doResume */, checkedOptions, inTask, outActivity);
        //......
    }
    

    接着又是调用startActivity:

    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                    int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                    ActivityRecord[] outActivity) {
            int result = START_CANCELED;
            try {
                mService.mWindowManager.deferSurfaceLayout();
                result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                        startFlags, doResume, options, inTask, outActivity);
            } 
            //......
        }
    

    startActivityUnchecked中调用ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法:

    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
        //......
        mSupervisor.resumeFocusedStackTopActivityLocked();
        //......
    }
    

    7.ActivityStackSupervisor

    ActivityStackSurpervisor是用于管理Activity堆栈的。
    进入resumeFocusedStackTopActivityLocked方法后,调用ActivityStarter解析出的目标栈的resumeTopActivityUncheckedLocked方法:

    boolean resumeFocusedStackTopActivityLocked(
                ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
            //.....
            if (targetStack != null && isFocusedStack(targetStack)) {
                return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
            //......
        }
    

    8、ActivityStack

    ActivityStack是单个堆栈的状态和管理,管理是单个堆栈内所有activity及其状态。
    进入resumeTopActivityUncheckedLocked之后,接着调用resumeTopActivityInnerLocked方法:

    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
           //......
           result = resumeTopActivityInnerLocked(prev, options);
          //......
    }
    

    resumeTopActivityInnerLocked方法又调用ActivityStackSupervisor的startSpecificActivityLocked:

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        //......
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
        //......
    }
    
    8.1回到ActivityStackSupervisor的startSpecificActivityLocked方法:
    void startSpecificActivityLocked(ActivityRecord r,
                boolean andResume, boolean checkConfig) {
            // Is this activity's application already running?
            //mService即AMS,根据应用信息uid、进程名获取所属的进程记录
            ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                    r.info.applicationInfo.uid, true);
    
            getLaunchTimeTracker().setLaunchTime(r);
    
            if (app != null && app.thread != null) {
                //进程已经存在
                try {
                    if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                            || !"android".equals(r.info.packageName)) {
                        // Don't add this if it is a platform component that is marked
                        // to run in multiple processes, because this is actually
                        // part of the framework so doesn't make sense to track as a
                        // separate apk in the process.
                        app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                                mService.mProcessStats);
                    }
                    //进程已经存在接着调用realStartActivityLocked继续activity的启动
                    realStartActivityLocked(r, app, andResume, checkConfig);
                    return;
                } catch (RemoteException e) {
                    Slog.w(TAG, "Exception when starting activity "
                            + r.intent.getComponent().flattenToShortString(), e);
                }
    
                // If a dead object exception was thrown -- fall through to
                // restart the application.
            }
            //进程不存在,则调用AMS的startProcessLocked进行创建进程
            mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                    "activity", r.intent.getComponent(), false, false, true);
        }
    
    8.2进程不存在时,回到AMS先创建进程
    @GuardedBy("this")
        final ProcessRecord startProcessLocked(String processName,
                ApplicationInfo info, boolean knownToBeDead, int intentFlags,
                String hostingType, ComponentName hostingName, boolean allowWhileBooting,
                boolean isolated, boolean keepIfLarge) {
            return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
                    hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                    null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                    null /* crashHandler */);
        }
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
                boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
                boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
                String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
        //......
        final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
        //......
    }
    private final boolean startProcessLocked(ProcessRecord app,
                String hostingType, String hostingNameStr, String abiOverride) {
            return startProcessLocked(app, hostingType, hostingNameStr,
                    false /* disableHiddenApiChecks */, abiOverride);
    }
    private final boolean startProcessLocked(ProcessRecord app, String hostingType,
                String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
        //......
        return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                        runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                        startTime);
        //......
    }
    private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
                ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
                String seInfo, String requiredAbi, String instructionSet, String invokeWith,
                long startTime) {
        //......
        final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
                                app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
                                requiredAbi, instructionSet, invokeWith, app.startTime);
       synchronized (ActivityManagerService.this) {
               handleProcessStartedLocked(app, startResult, startSeq);
       }
        //......
    }
    private ProcessStartResult startProcess(String hostingType, String entryPoint,
                ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
                String seInfo, String requiredAbi, String instructionSet, String invokeWith,
                long startTime) {
        //......
        startResult = Process.start(entryPoint,
                            app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                            app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                            app.info.dataDir, invokeWith,
                            new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        //......
    }
    

    AMS中经过层层startProcessLocked的调用,最后进入startProcess方法,startProcess方法调用Process的start方法开始创建进程

    8.2.1、Proccess

    Proccess的start是个静态方法,其直接调用ZygoteProcess的start方法:

    public static final ProcessStartResult start(final String processClass,
                                      final String niceName,
                                      int uid, int gid, int[] gids,
                                      int runtimeFlags, int mountExternal,
                                      int targetSdkVersion,
                                      String seInfo,
                                      String abi,
                                      String instructionSet,
                                      String appDataDir,
                                      String invokeWith,
                                      String[] zygoteArgs) {
            return zygoteProcess.start(processClass, niceName, uid, gid, gids,
                        runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                        abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
        }
    
    8.2.2 ZygoteProcess 创建App进程

    ZygoteProcess的start方法接着调用startViaZygote:

    public final Process.ProcessStartResult start(final String processClass,
                                                      final String niceName,
                                                      int uid, int gid, int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      String seInfo,
                                                      String abi,
                                                      String instructionSet,
                                                      String appDataDir,
                                                      String invokeWith,
                                                      String[] zygoteArgs) {
            try {
                return startViaZygote(processClass, niceName, uid, gid, gids,
                        runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                        abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
                        zygoteArgs);
            } catch (ZygoteStartFailedEx ex) {
                Log.e(LOG_TAG,
                        "Starting VM process through Zygote failed");
                throw new RuntimeException(
                        "Starting VM process through Zygote failed", ex);
            }
        }
    

    startViaZygote方法组织Zygote的参数,接着调用zygoteSendArgsAndGetResult方法:

    private Process.ProcessStartResult startViaZygote(final String processClass,
                                                          final String niceName,
                                                          final int uid, final int gid,
                                                          final int[] gids,
                                                          int runtimeFlags, int mountExternal,
                                                          int targetSdkVersion,
                                                          String seInfo,
                                                          String abi,
                                                          String instructionSet,
                                                          String appDataDir,
                                                          String invokeWith,
                                                          boolean startChildZygote,
                                                          String[] extraArgs)
                                                          throws ZygoteStartFailedEx {
        //......
        synchronized(mLock) {
                //openZygoteSocketIfNeeded创建本次通信的所所用的Socket
                return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
            }
        //......
    }
    

    zygoteSendArgsAndGetResult使用socket与zygote进行通信,将包装的参数通过socket传递给zygote,zygote收到之后,根据参数fork创建进程,并返回结果进程id:

    private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
                ZygoteState zygoteState, ArrayList<String> args)
                throws ZygoteStartFailedEx {
            try {
                // Throw early if any of the arguments are malformed. This means we can
                // avoid writing a partial response to the zygote.
                int sz = args.size();
                for (int i = 0; i < sz; i++) {
                    if (args.get(i).indexOf('\n') >= 0) {
                        throw new ZygoteStartFailedEx("embedded newlines not allowed");
                    }
                }
    
                /**
                 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
                 * Presently the wire format to the zygote process is:
                 * a) a count of arguments (argc, in essence)
                 * b) a number of newline-separated argument strings equal to count
                 *
                 * After the zygote process reads these it will write the pid of
                 * the child or -1 on failure, followed by boolean to
                 * indicate whether a wrapper process was used.
                 */
                final BufferedWriter writer = zygoteState.writer;
                final DataInputStream inputStream = zygoteState.inputStream;
                //将参数发送给zygote
                writer.write(Integer.toString(args.size()));
                writer.newLine();
    
                for (int i = 0; i < sz; i++) {
                    String arg = args.get(i);
                    writer.write(arg);
                    writer.newLine();
                }
    
                writer.flush();
    
                // Should there be a timeout on this?
                Process.ProcessStartResult result = new Process.ProcessStartResult();
    
                // Always read the entire result from the input stream to avoid leaving
                // bytes in the stream for future process starts to accidentally stumble
                // upon.
                //读取响应结果,获取创建的进程id
                result.pid = inputStream.readInt();
                result.usingWrapper = inputStream.readBoolean();
    
                if (result.pid < 0) {
                    //fork创建进程失败
                    throw new ZygoteStartFailedEx("fork() failed");
                }
                return result;
            } catch (IOException ex) {
                zygoteState.close();
                throw new ZygoteStartFailedEx(ex);
            }
        }
    

    进程的创建过程是通过Socket将参数传递给zygote,zygote拿到参数之后通过fork创建出所需的子进程,此子进程即App的进程。

    8.2.3 启动App主线程

    App进程的入口在ActivityThread的main方法:

    public static void main(String[] args) {
        //......
        //Looper构建主线程
        Looper.prepareMainLooper();
        //.......
        //创建ActivityThread
        ActivityThread thread = new ActivityThread();
       //调用attach
        thread.attach(false, startSeq);
    
        if (sMainThreadHandler == null) {
            //设置主线程
            sMainThreadHandler = thread.getHandler();
        }
        //......
        //进入Looper死循环
        Looper.loop();
        //......
    }
    

    new ActivityThread时同时创建了主线程Handler、ApplicationThread、资源管理器等,其中ApplicationThread是一个Binder,在启动Activity时会传递给AMS供AMS回调响应,以下是new ActivityThread:

    //......
    final H mH = new H();
    final ApplicationThread mAppThread = new ApplicationThread();
    //......
    ActivityThread() {
            mResourcesManager = ResourcesManager.getInstance();
    }
    

    我们再看看ActivityThread的attach:

    private void attach(boolean system, long startSeq) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            if (!system) {
              //此处system为false,非系统线程
               //......
                RuntimeInit.setApplicationObject(mAppThread.asBinder());
                //又通过ActivityManager获取AMS
                final IActivityManager mgr = ActivityManager.getService();
                try {
                    //调用AMS的attachApplication方法
                    mgr.attachApplication(mAppThread, startSeq);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
        }
        //......
    }
    

    ActivityThread的attach又调用AMS的attachApplication对Application进行进程上的绑定:
    我们接着看AMS的attachApplication:

    private final boolean attachApplicationLocked(IApplicationThread thread,
                int pid, int callingUid, long startSeq) {
         //......
        //此处的thread即上一步ActivityThread中的mAppThread,它是一个binder,又是进程间通信回到ActivityThread中的mAppThread创建Application
        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);
         //......
        // See if the top visible activity is waiting to run in this process...
        //创建完application,看看是否有等待运行的activity
            if (normalMode) {
                try {
                    if (mStackSupervisor.attachApplicationLocked(app)) {
                        didSomething = true;
                    }
                } catch (Exception e) {
                    Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                    badApp = true;
                }
            }
        //......
    }
    

    AMS的attachApplicationLocked主要有两件事:

    • 进程间通信回到ActivityThread的mAppThread的bindApplication创建Application
    • 创建完Application之后,调用ActivityStackSurpervisor的attachApplicationLocked启动第一个Activity
    8.2.4 创建Application

    通过进程间通信从AMS切换ActivityThread的mAppThread(是ApplicationThread的实例)的bindApplication方法:

    public final void bindApplication(String processName, ApplicationInfo appInfo,
                    List<ProviderInfo> providers, 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, boolean autofillCompatibilityEnabled) {
        //......
        sendMessage(H.BIND_APPLICATION, data);
        //......
    }
    

    ApplicaitonThread.Stub的bindApplication调用ActivityThread的sendMessage,事件是BIND_APPLICATION,ActivityThread的sendMessage最终调用mH(H类的实现类)即主线程的Handler,进行发送消息:

    void sendMessage(int what, Object obj) {
            sendMessage(what, obj, 0, 0, false);
    }
    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
            if (DEBUG_MESSAGES) Slog.v(
                TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                + ": " + arg1 + " / " + obj);
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            if (async) {
                msg.setAsynchronous(true);
            }
            mH.sendMessage(msg);
        }
    

    我们看看mH的的handleMessage方法中事件是BIND_APPLICATION的分支:

    public void handleMessage(Message msg) {
                if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
                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方法:

    private void handleBindApplication(AppBindData data) {
        //......
        //创建App上下文Context
        final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
        //......
        if (ii != null) {
                ApplicationInfo instrApp;
                try {
                    //获取应用信息
                    instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
                            UserHandle.myUserId());
                } catch (RemoteException e) {
                    instrApp = null;
                }
                if (instrApp == null) {
                    instrApp = new ApplicationInfo();
                }
                ii.copyTo(instrApp);
                instrApp.initForUser(UserHandle.myUserId());
                //构建已经加载的apk对象
                final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
                        appContext.getClassLoader(), false, true, false);
                //构建context上下文的实例instrContext 
                final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
    
                try {
                    //使用ContextImpl的classloader反射创建Instrumentation对象
                    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);
                }
    
                final ComponentName component = new ComponentName(ii.packageName, ii.name);
                //初始化Instrumentation
                mInstrumentation.init(this, instrContext, appContext, component,
                        data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
    
                if (mProfiler.profileFile != null && !ii.handleProfiling
                        && mProfiler.profileFd == null) {
                    mProfiler.handlingProfiling = true;
                    final File file = new File(mProfiler.profileFile);
                    file.getParentFile().mkdirs();
                    Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
                }
            } else {
                mInstrumentation = new Instrumentation();
                mInstrumentation.basicInit(this);
            }
        //.....
        Application app;
            try {
                // If the app is being launched for full backup or restore, bring it up in
                // a restricted environment with the base application class.
                //data.info是LoadedApk对象,使用LoadedApk.makeApplication创建Application
                app = data.info.makeApplication(data.restrictedBackupMode, null);
    
                // Propagate autofill compat state
                app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);
    
                mInitialApplication = app;
    
                // don't bring up providers in restricted mode; they may depend on the
                // app's custom Application class
                if (!data.restrictedBackupMode) {
                    if (!ArrayUtils.isEmpty(data.providers)) {
                        installContentProviders(app, data.providers);
                        // For process that contains content providers, we want to
                        // ensure that the JIT is enabled "at some point".
                        mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
                    }
                }
    
                // Do this after providers, since instrumentation tests generally start their
                // test thread at this point, and we don't want that racing.
                try {
                    //回调Instrumentation的onCreate方法,告知Instrument已经创建
                    mInstrumentation.onCreate(data.instrumentationArgs);
                }
                catch (Exception e) {
                    throw new RuntimeException(
                        "Exception thrown in onCreate() of "
                        + data.instrumentationName + ": " + e.toString(), e);
                }
                try {
                    //通过Instrumentation的onCreate回调Application的onCreate方法
                    mInstrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                    if (!mInstrumentation.onException(app, e)) {
                        throw new RuntimeException(
                          "Unable to create application " + app.getClass().getName()
                          + ": " + e.toString(), e);
                    }
                }
            }
    
        //......    
    }
    

    LoaderApk的makeApplication如下:

    public Application makeApplication(boolean forceDefaultAppClass,
                Instrumentation instrumentation) {
        //......    
            try {
                java.lang.ClassLoader cl = getClassLoader();
                if (!mPackageName.equals("android")) {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                            "initializeJavaContextClassLoader");
                    initializeJavaContextClassLoader();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                }
                //创建app上下文实例appContext 
                ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
                //调用Instrumentation的newApplication方法创建Application
                app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
                appContext.setOuterContext(app);
            } catch (Exception e) {
                if (!mActivityThread.mInstrumentation.onException(app, e)) {
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    throw new RuntimeException(
                        "Unable to instantiate application " + appClass
                        + ": " + e.toString(), e);
                }
            }
        //......    
    }
    

    Instrumentation的newApplication方法如下:

    public Application newApplication(ClassLoader cl, String className, Context context)
                throws InstantiationException, IllegalAccessException, 
                ClassNotFoundException {
            //创建Application
            Application app = getFactory(context.getPackageName())
                    .instantiateApplication(cl, className);
           //Application绑定Context,作为ApplicationContext
            app.attach(context);
            return app;
        }
    

    Instrumentation的newApplication中调用getFactory获取Application组件工厂类AppComponentFactory,工厂类AppComponentFactory的instantiateApplication创建Application,AppComponentFactory的instantiateApplication方法如下:

    public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
                @NonNull String className)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return (Application) cl.loadClass(className).newInstance();
        }
    

    AppComponentFactory.instantiateApplication使用clossloader加载Application的实现类newInstance创建Application。
    回到ActivityThread创建Application流程中的handleBindApplication创建完Application之后的步骤:

      try {
                    //回到Instrumentation的onCreate
                    mInstrumentation.onCreate(data.instrumentationArgs);
                }
                catch (Exception e) {
                    throw new RuntimeException(
                        "Exception thrown in onCreate() of "
                        + data.instrumentationName + ": " + e.toString(), e);
                }
                try {
                    //回到Instrumentation的callApplicationOnCreate
                    mInstrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                    if (!mInstrumentation.onException(app, e)) {
                        throw new RuntimeException(
                          "Unable to create application " + app.getClass().getName()
                          + ": " + e.toString(), e);
                    }
                }
    

    Instrumentation的onCreate中啥也不做,callApplicationOnCreate方法中调用Application的onCreate方法:

    public void onCreate(Bundle arguments) {
        }
    public void callApplicationOnCreate(Application app) {
            app.onCreate();
        }
    

    至此Appliation创建完成。

    8.2.5 创建Activity

    回到8.2.3步骤中AMS创建Application的步骤方法attachApplicationLocked,attachApplicationLocked调用ActivityThread.bindApplication创建Application之后,接着:

    private final boolean attachApplicationLocked(IApplicationThread thread,
                int pid, int callingUid, long startSeq) {
         //......
        //此处的thread即上一步ActivityThread中的mAppThread,它是一个binder,又是进程间通信回到ActivityThread中的mAppThread创建Application
        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);
         //......
        // See if the top visible activity is waiting to run in this process...
        //创建完application,看看是否有等待运行的activity
            if (normalMode) {
                try {
                    if (mStackSupervisor.attachApplicationLocked(app)) {
                        didSomething = true;
                    }
                } catch (Exception e) {
                    Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
                    badApp = true;
                }
            }
        //......
    }
    

    接着调用ActivitySupervisor的attachApplicationLocked方法,我们看看attachApplicationLocked方法:

    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        //......
        if (realStartActivityLocked(activity, app,
                                        top == activity /* andResume */, true /* checkConfig */)) {
                                    didSomething = true;
                                }
        //......
    }
    

    ActivitySupervisor的realStartActivityLocked方法如下:

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                boolean andResume, boolean checkConfig) throws RemoteException {
        //......
        // Create activity launch transaction.
                    //创建Activity启动事务
                    final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                            r.appToken);
                    //创建LaunchActivityItem对象,传入Activity启动事务作为callback
                    clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                            System.identityHashCode(r), r.info,
                            // TODO: Have this take the merged configuration instead of separate global
                            // and override configs.
                            mergedConfiguration.getGlobalConfiguration(),
                            mergedConfiguration.getOverrideConfiguration(), r.compat,
                            r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                            r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                            profilerInfo));
    
                    // Set desired final state.
                    final ActivityLifecycleItem lifecycleItem;
                    //这里andResume为true
                    if (andResume) {
                        //创建ResumeActivityItem对象,作为前一个Activity onResume生命周期的回调
                        lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
                    } else {
                        //创建PauseActivityItem对象,作为前一个Activity onPause生命周期的回调
                        lifecycleItem = PauseActivityItem.obtain();
                    }
                    clientTransaction.setLifecycleStateRequest(lifecycleItem);
    
                    // Schedule transaction.
                    //通过AMS获取生命周期管理者ClientLifecycleManager,然后调度本次Activity的启动事务
                    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
        //......
    }
    

    我们直接进入生命周期管理者ClientLifecycleManager的scheduleTransaction方法:

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
            final IApplicationThread client = transaction.getClient();
            transaction.schedule();
            if (!(client instanceof Binder)) {
                // If client is not an instance of Binder - it's a remote call and at this point it is
                // safe to recycle the object. All objects used for local calls will be recycled after
                // the transaction is executed on client in ActivityThread.
                transaction.recycle();
            }
        }
    

    ClientLifecycleManager的scheduleTransaction方法直接调用ClientTransaction 的schedule方法,我们接着看ClientTransaction 的schedule方法:

    public void schedule() throws RemoteException {
            mClient.scheduleTransaction(this);
        }
    

    ClientTransaction 的schedule方法直接调用ApplicationThread的scheduleTransaction,又是一次进程间通信,我们接着看ApplicationThread的scheduleTransaction:

    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
                ActivityThread.this.scheduleTransaction(transaction);
            }
    

    ApplicationThread的scheduleTransaction接着调用ActivityThread的scheduleTransaction方法,ActivityThread继承了ClientTransactionHandler,scheduleTransaction是在ClientTransactionHandler实现的:

    void scheduleTransaction(ClientTransaction transaction) {
            transaction.preExecute(this);
            sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
        }
    

    ClientTransactionHandler接着调用sendMessage发送EXECUTE_TRANSACTION事件,sendMessage是抽象方法,其实现由ActivityThread实现,ActivityThread使用mH发出EXECUTE_TRANSACTION事件之后,接着事件进入ActivityThread的H的handleMessage的EXECUTE_TRANSACTION分支中处理:

    case EXECUTE_TRANSACTION:
                        final ClientTransaction transaction = (ClientTransaction) msg.obj;
                        mTransactionExecutor.execute(transaction);
                        if (isSystem()) {
                            // Client transactions inside system process are recycled on the client side
                            // instead of ClientLifecycleManager to avoid being cleared before this
                            // message is handled.
                            transaction.recycle();
                        }
    

    ActivityThread的H的handleMessage的EXECUTE_TRANSACTION分支接着调用

    8.3进程已经存在则进入ActivityStackSupervisor的realStartActivityLocked方法:TransactionExecutor.execute的方法,我们接着看TransactionExecutor.execute:
    public void execute(ClientTransaction transaction) {
            final IBinder token = transaction.getActivityToken();
            log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
    
            executeCallbacks(transaction);
    
            executeLifecycleState(transaction);
            mPendingActions.clear();
            log("End resolving transaction");
        }
    

    TransactionExecutor.execute接着调用executeCallbacks方法:

     public void executeCallbacks(ClientTransaction transaction) {
            //callback其实里面就是LaunchActivityItem
            final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        //......
        final int size = callbacks.size();
      for (int i = 0; i < size; ++i) {
                //遍历待事务列表
                final ClientTransactionItem item = callbacks.get(i);
                //......
                //调用事务的excute方法,这里是LaunchActivityItem
                item.execute(mTransactionHandler, token, mPendingActions);
                item.postExecute(mTransactionHandler, token, mPendingActions);
              //......
        }
        //......
    }
    

    TransactionExecutor的executeCallbacks方法遍历事务列表,记得上面介绍时事务列表里面主要是LaunchActivityItem事务即启动Activity事务,接着调用LaunchActivityItem的execute方法,我们继续看LaunchActivityItem的execute方法,:

    public void execute(ClientTransactionHandler client, IBinder token,
                PendingTransactionActions pendingActions) {
            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
            ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                    mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                    mPendingResults, mPendingNewIntents, mIsForward,
                    mProfilerInfo, client);
            client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    

    这里的client是ClientTransactionHandler,而ActivityThread继承了ClientTransactionHandler ,所以又回到ActivityThread,进入ActivityThread的handleLaunchActivity方法:

    public Activity handleLaunchActivity(ActivityClientRecord r,
                PendingTransactionActions pendingActions, Intent customIntent) {
        //......
       //初始化WindowManagerService
        WindowManagerGlobal.initialize();
        //调用performLaunchActivity创建Activity
        final Activity a = performLaunchActivity(r, customIntent);
         //......
    }
    

    ActivityThread的handleLaunchActivity调用performLaunchActivity来启动Activity:

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //......
        //创建Activity关联的上下文
        ContextImpl appContext = createBaseContextForActivity(r);
            Activity activity = null;
            try {
                //获取上下文的classloader
                java.lang.ClassLoader cl = appContext.getClassLoader();
                //使用上下文的classloader,通过Instrumentation创建Activity
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
                StrictMode.incrementExpectedActivityCount(activity.getClass());
                r.intent.setExtrasClassLoader(cl);
                r.intent.prepareToEnterProcess();
                if (r.state != null) {
                    r.state.setClassLoader(cl);
                }
            }
        //......
        Window window = null;
        if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                        window = r.mPendingRemoveWindow;
                        r.mPendingRemoveWindow = null;
                        r.mPendingRemoveWindowManager = null;
        }
       appContext.setOuterContext(activity);
      //调用activity的attach绑定上下文context、Instrumentation、Application、window等
      activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback);
    
       //......
      //接着调用Instrumentation的callActivityOnCreate回调Activity的onCreate方法
      if (r.isPersistable()) {
           mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
     } else {
            mInstrumentation.callActivityOnCreate(activity, r.state);
      }          
        //......
    }
    

    ActivityThread的performLaunchActivity方法中,先是构建Activity关联的上下文Context,接着使用调用Instrumentation的newActivity方法使用上下文Context的classloader进行反射创建Activity,然后调用activity的attach方法与上下文context、Instrumentation、Application、window等进行关联,接着使用Instrumentation的callActivityOnCreate回调activity的onCreate方法。
    我们看看Instrumentation的newActivity:

    public Activity newActivity(ClassLoader cl, String className,
                Intent intent)
                throws InstantiationException, IllegalAccessException,
                ClassNotFoundException {
            String pkg = intent != null && intent.getComponent() != null
                    ? intent.getComponent().getPackageName() : null;
            return getFactory(pkg).instantiateActivity(cl, className, intent);
        }
    
    //android.app.AppComponentFactory.instantiateActivity
    public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
                @Nullable Intent intent)
                throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return (Activity) cl.loadClass(className).newInstance();
        }
    

    Instrumentation的newActivity最终使用上下文的classloader加载activity类并newInstance创建activity实例。
    我们接着看Instrumentation的callActivityOnCreate方法:

    public void callActivityOnCreate(Activity activity, Bundle icicle,
                PersistableBundle persistentState) {
            prePerformCreate(activity);
            activity.performCreate(icicle, persistentState);
            postPerformCreate(activity);
        }
    

    Instrumentation的callActivityOnCreate方法接着调用activity的performCreate方法:

    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
            mCanEnterPictureInPicture = true;
            restoreHasCurrentPermissionRequest(icicle);
            if (persistentState != null) {
                onCreate(icicle, persistentState);
            } else {
                onCreate(icicle);
            }
            writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
            mActivityTransitionState.readState(icicle);
    
            mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                    com.android.internal.R.styleable.Window_windowNoDisplay, false);
            mFragments.dispatchActivityCreated();
            mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        }
    

    activity的performCreate方法接着调用activity的onCreate方法。
    到这里已经完成了Activity的onCreate生命周期,那么onStart呢?我们回到上面的TransactionExecutor.execute的方法:

    public void execute(ClientTransaction transaction) {
            final IBinder token = transaction.getActivityToken();
            log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
            //执行的是callback事务,即启动Activity的事务LaunchActivityItem
            executeCallbacks(transaction);
            //执行生命周期事务
            executeLifecycleState(transaction);
            mPendingActions.clear();
            log("End resolving transaction");
        }
    

    我们接着看TransactionExecutor的executeLifecycleState方法:

    private void executeLifecycleState(ClientTransaction transaction) {
            //获取生命周期请求事务,上面ActivitySupervisor中有接收是ResumeActivityItem事务
            final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
            if (lifecycleItem == null) {
                // No lifecycle request, return early.
                return;
            }
            log("Resolving lifecycle state: " + lifecycleItem);
    
            final IBinder token = transaction.getActivityToken();
            final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    
            if (r == null) {
                // Ignore requests for non-existent client records for now.
                return;
            }
            //调用cycleToPath完成activity的启动生命周期
            // Cycle to the state right before the final requested state.
            cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
    
            // Execute the final transition with proper parameters.
            //调用ResumeActivityItem事务的execute
            lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
            lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
        }
    

    我们接着看cycleToPath是怎么完成启动的Activity的生命周期:

    private void cycleToPath(ActivityClientRecord r, int finish,
                boolean excludeLastState) {
            final int start = r.getLifecycleState();
            log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
            final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
            performLifecycleSequence(r, path);
        }
    

    cycleToPath拿到当前activity的状态即ON_Create+1和finish即ResumeActivityItem的状态即ON_RESUME,构建本次要继续完成的生命周期区间(不包括ON_RESUME),调用performLifecycleSequence完成剩下的生命周期:ON_START:

    private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
            final int size = path.size();
            for (int i = 0, state; i < size; i++) {
                state = path.get(i);
                log("Transitioning to state: " + state);
                switch (state) {
                    case ON_CREATE:
                        mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                                null /* customIntent */);
                        break;
                    case ON_START:
                        mTransactionHandler.handleStartActivity(r, mPendingActions);
                        break;
                    case ON_RESUME:
                        mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                                r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                        break;
                    case ON_PAUSE:
                        mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                                false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                                "LIFECYCLER_PAUSE_ACTIVITY");
                        break;
                    case ON_STOP:
                        mTransactionHandler.handleStopActivity(r.token, false /* show */,
                                0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                                "LIFECYCLER_STOP_ACTIVITY");
                        break;
                    case ON_DESTROY:
                        mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                                0 /* configChanges */, false /* getNonConfigInstance */,
                                "performLifecycleSequence. cycling to:" + path.get(size - 1));
                        break;
                    case ON_RESTART:
                        mTransactionHandler.performRestartActivity(r.token, false /* start */);
                        break;
                    default:
                        throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
                }
            }
        }
    

    cycleToPath方法一目了然,这里遍历剩下的生命周期区间:ON_START,依次走ON_START分支。
    其中ON_START分支调用mTransactionHandler.handleStartActivity方法,
    mTransactionHandler是ActivityThread,所以我们进入ActivityThread的handleStartActivity方法:

    public void handleStartActivity(ActivityClientRecord r,
                PendingTransactionActions pendingActions) {
            //......
            // Start
            activity.performStart("handleStartActivity");
           //......
    }
    //android.app.Activity.performStart
    final void performStart(String reason) {
            mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
            mFragments.noteStateNotSaved();
            mCalled = false;
            mFragments.execPendingActions();
            mInstrumentation.callActivityOnStart(this);
          //......
    }
    //Instrumentation.callActivityOnStart
    public void callActivityOnStart(Activity activity) {
            activity.onStart();
        }
    

    接着走ResumeActivityItem的execute方法:

    public void execute(ClientTransactionHandler client, IBinder token,
                PendingTransactionActions pendingActions) {
            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
            client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                    "RESUME_ACTIVITY");
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    

    ResumeActivityItem的execute调用ClientTransactionHandler的handleResumeActivity方法,而ActivityThread是ClientTransactionHandler的实现类,我们接着看ActivityThread的handleResumeActivity方法

    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
                String reason) {
        //.....
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        //.....
    }
    public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
                String reason) {
        //......
        r.activity.performResume(r.startsNotResumed, reason);
        //......
    }
    //android.app.Activity.performResume
    final void performResume(boolean followedByPause, String reason) {
        //......
        mInstrumentation.callActivityOnResume(this);
        //......
    }
    //Instrumentation.callActivityOnResume
    public void callActivityOnResume(Activity activity) {
            activity.mResumed = true;
            activity.onResume();
           //......
    }
    

    到此完成启动activity的生命周期。

    8.3进程存在时,调用ActivityStackSupervisor的realStartActivityLocked

    此步骤与8.2中的创建完进程及Application之后,调用ActivityStackSupervisor的realStartActivityLocked进行创建启动Activity一样,在此不做重复。

    到此Activity的启动流程介绍完毕。

    问题1:为什么与zygote通信使用socket而不是Binder?
    解答:(注参考网上别人的说法)
    a、zygote进行fork子进程不允许在线程中进行操作,因为子线程fork子进程会造成死锁。而Binder使用通信又是在子进程中进行
    b、zygote如果用Binder机制可能会因BInder线程池(默认16个线程)满而造成延迟,进而导致ANR

    相关文章

      网友评论

          本文标题:Android启动流程

          本文链接:https://www.haomeiwen.com/subject/oyptsrtx.html