• APP启动流程一(源码30)之向Zygote发送创建APP进程的请求


    APP启动流程二(源码30)之APP进程创建
    APP启动流程三(源码30)之APP进程启动及Activity启动

    在这里插入图片描述

    AMS.systemReady()中启动Launcher

    if (bootingSystemUser) {
        t.traceBegin("startHomeOnAllDisplays");
        mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        t.traceEnd();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    Laucher进程
    Zygote进程

    Launcher进程–>Activity.startActivity–>startActivityForResult

    Activity.startActivityForResult()

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this,mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(),ar.getResultData());
                
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }
            cancelInputsAndStartExitTransition(options);
            // TODO Consider clearing/flushing other event sources and events for child windows.
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Instrumentation.execStartActivity()

    //ActivityTaskManagerService.startActivity()-->startActivityAsUser()
    int result = ActivityTaskManager.getService().startActivity(whoThread,who.getBasePackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token,target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
    
    • 1
    • 2

    ActivityTaskManager.getService()

    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    
    //返回ActivityTaskManagerService
    @UnsupportedAppUsage(trackingBug = 129726065)
    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() {
        @Override
        protected IActivityTaskManager create() {
            final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
            return IActivityTaskManager.Stub.asInterface(b);
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    ActivityTaskManagerService.startActivityAsUser()

    private int startActivityAsUser(IApplicationThread caller, String callingPackage,@Nullable String callingFeatureId, Intent intent, String resolvedType,IBinder resultTo, String resultWho, int requestCode, int startFlags,ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
        assertPackageMatchesCallingUid(callingPackage);
        enforceNotIsolatedCaller("startActivityAsUser");
    
        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    
        //ActivityStarter.execute()
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setCallingFeatureId(callingFeatureId)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setUserId(userId)
                .execute();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    ActivityStarter.execute()–>startActivityUnchecked()–>startActivityInner()

    ActivityStarter.startActivityInner()

    • 根据启动标志位和Activity启动模式判断如何启动一个Activity
    //判断是否调用deliverNewIntent()通知Activity有一个Intent视图启动它
    if (topStack != null) {
    	startResult = deliverToCurrentTopIfNeeded(topStack, intentGrants);
    	if (startResult != START_SUCCESS) {
    	    return startResult;
    	}
    }
    
    if (mDoResume) {
        final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isTopActivityFocusable()|| (topTaskActivity != null&& topTaskActivity.isTaskOverlay()&& mStartActivity != topTaskActivity)) {
            mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
        } else {
            // If the target stack was not previously focusable (previous top running activity
            // on that stack was not visible) then any prior calls to move the stack to the
            // will not update the focused stack.  If starting the new activity now allows the
            // task stack to be focusable, then ensure that we now update the focused stack
            // accordingly.
            if (mTargetStack.isTopActivityFocusable()
                    && !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityInner");
            }
            //开始resume我们的Activity
            mRootWindowContainer.resumeFocusedStacksTopActivities(
                    mTargetStack, mStartActivity, mOptions);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    RootWindowContainer.resumeFocusedStacksTopActivities()

    boolean result = false;
    if (targetStack != null && (targetStack.isTopStackInDisplayArea()
            || getTopDisplayFocusedStack() == targetStack)) {
        result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ActivityStack.resumeTopActivityUncheckedLocked()–>resumeTopActivityInnerLocked()–>ActivityStackSupervisor.startSpecificActivity


    ActivityStackSupervisor.startSpecificActivity判断是否需要新建app进程

    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
    	// Is this activity's application already running?
    	final WindowProcessController wpc =
    	mService.getProcessController(r.processName, r.info.applicationInfo.uid);
    	
    	boolean knownToBeDead = false;
    	if (wpc != null && wpc.hasThread()) {//app进程已创建
    	    try {
    	    	//启动Activity
    	        realStartActivityLocked(r, wpc, 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.
    	    knownToBeDead = true;
    	}
    	
    	r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
    	
    	final boolean isTop = andResume && r.isTopRunningActivity();
    	//进程还没创建,app没有启动
    	mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    ActivityTaskManagerService.startProcessAsync()后续流程是向Zygote通信请求创建 app进程

    void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,String hostingType) {
    try {
        if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
                    + activity.processName);
        }
        // Post message to start process to avoid possible deadlock of calling into AMS with the
        // ATMS lock held.
        final Message m =
        /**
        ** 1.ActivityManagerInternal是一个抽象类,其实现类是ActiManagerService里的LocalService
        ** 2.一个规律:在源码里面发现类似xxxInternal的抽象类,实现类往往是xxxService里面的LocalService
        **/
        PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead, isTop, hostingType, activity.intent.getComponent());
        mH.sendMessage(m);
    } finally {
        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    ActivityManagerService.LocalService.startProcess()–>ActivityManagerService.startProcessLocked–>ProcessList.startProcessLocked

    ProcessList.startProcessLocked()

    // Start the process.  It will either succeed and return a result containing
    // the PID of the new process, or else throw a RuntimeException.
    final String entryPoint = "android.app.ActivityThread";
    
    return startProcessLocked(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ProcessList.startProcess()

    final Process.ProcessStartResult startResult;
        if (hostingRecord.usesWebviewZygote()) {//webview
            startResult = startWebView(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,
                    new String[]{PROC_START_SEQ_IDENT + app.startSeq});
        } else if (hostingRecord.usesAppZygote()) {
            //创建AppZygote对象
            final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
        
            // We can't isolate app data and storage data as parent zygote already did that.
            //AppZygote.getProcess() = ChildZygoteProcess
            //ChildZygoteProcess extends ZygoteProcess
            startResult = appZygote.getProcess().start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, null, app.info.packageName,
                    /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
                    app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap,
                    false, false,
                    new String[]{PROC_START_SEQ_IDENT + app.startSeq});
        } else {
            startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags,
                    isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap,
                    whitelistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs,
                    new String[]{PROC_START_SEQ_IDENT + app.startSeq});
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    ZygoteProcess.start()–>ZygoteProcess.startViaZygote()

    ZygoteProcess.startViaZygote()

    synchronized(mLock) {
        // The USAP pool can not be used if the application will not use the systems graphics
        // driver.  If that driver is requested use the Zygote application start path.
        return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                          zygotePolicyFlags,
                                          argsForZygote);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ZygoteProcess.openZygoteSocketIfNeeded()–>ZygoteProcess.attemptConnectionToPrimaryZygote()–>ZygoteState.connect()

    ZygoteState.connect()

    static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,@Nullable LocalSocketAddress usapSocketAddress)throws IOException {
        
        DataInputStream zygoteInputStream;
        BufferedWriter zygoteOutputWriter;
        final LocalSocket zygoteSessionSocket = new LocalSocket();
        
        if (zygoteSocketAddress == null) {
            throw new IllegalArgumentException("zygoteSocketAddress can't be null");
        }
        
        try {
            //通过socket连接zygote
            zygoteSessionSocket.connect(zygoteSocketAddress);
            zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
            zygoteOutputWriter = new BufferedWriter(new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),Zygote.SOCKET_BUFFER_SIZE);
        } catch (IOException ex) {
            try {
                zygoteSessionSocket.close();
            } catch (IOException ignore) { }
        
            throw ex;
        }
        
        return new ZygoteState(zygoteSocketAddress, usapSocketAddress,zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,getAbiList(zygoteOutputWriter, zygoteInputStream));
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    ZygoteProcess.zygoteSendArgsAndGetResult()

    //USAP进程启动优化机制
    //判断是使用usap启动app进程还是直接fork
    if (shouldAttemptUsapLaunch(zygotePolicyFlags, args)) {
            try {
                return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
            } catch (IOException ex) {
                // If there was an IOException using the USAP pool we will log the error and
                // attempt to start the process through the Zygote.
                Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "
                        + ex.getMessage());
            }
        }
    
        return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    ZygoteProcess.attemptUsapSendArgsAndGetResult()

    //向zygote进程发送消息请求创建app进程
    private Process.ProcessStartResult attemptUsapSendArgsAndGetResult(ZygoteState zygoteState, String msgStr)throws ZygoteStartFailedEx, IOException {
        try (LocalSocket usapSessionSocket = zygoteState.getUsapSessionSocket()) {
            final BufferedWriter usapWriter = new BufferedWriter(new OutputStreamWriter(usapSessionSocket.getOutputStream()), Zygote.SOCKET_BUFFER_SIZE);
            final DataInputStream usapReader = new DataInputStream(usapSessionSocket.getInputStream());
    
            usapWriter.write(msgStr);
            usapWriter.flush();
    
            Process.ProcessStartResult result = new Process.ProcessStartResult();
            result.pid = usapReader.readInt();
            // USAPs can't be used to spawn processes that need wrappers.
            result.usingWrapper = false;
    
            if (result.pid >= 0) {
                return result;
            } else {
                throw new ZygoteStartFailedEx("USAP specialization failed");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    接下篇 APP启动流程二(源码30)之APP进程创建

  • 相关阅读:
    linux之/etc/skel目录
    如何使用libswscale库将YUV420P格式的图像序列转换为RGB24格式输出?
    Anaconda下 Prophet的安装,pystan和fbprophet的版本问题
    Python爬虫库urllib使用详解
    基于React+antd的环境监测网站的设计与实现
    阿里架构师分享,想进大厂?数据结构和算法是你必过的一道坎
    docker安装redis
    BIO、NIO、AIO有什么区别
    浏览器的 5 种 Observer
    java特种兵读书笔记(4-3)——java通信之IO与通信调度方式
  • 原文地址:https://blog.csdn.net/Super_666/article/details/126248424