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();
}
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.
    }
}

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);

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);
    }
};

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();

}

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);
    }
}

RootWindowContainer.resumeFocusedStacksTopActivities()

boolean result = false;
if (targetStack != null && (targetStack.isTopStackInDisplayArea()
        || getTopDisplayFocusedStack() == targetStack)) {
    result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}

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");
}

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);
}
}

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);

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});
    }

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);
}

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));
 }

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);

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");
        }
    }
}

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值