[start-activity]ActivityManagerService-startactivity-func

目录

概述

在launcher中点击应用来启动应用。

1. 调用流程

1.1 start-activity-call

ActivityTaskManagerService类:startActivity
    -> ActivityStarter类:startActivityMayWait
        -> mSupervisor.getActivityMetricsLogger().notifyActivityLaunching:log打印debug:notifyActivityLaunching: active:false, intent:Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] }
        -> ActivityStackSupervisor类:resolveIntent
            -> PackageManagerInternalImpl类:resolveIntent:根据intent获取resolveInfo的信息,也就是manifest.xml中的信息
        -> ActivityStackSupervisor类:resolveActivity:根据resolveInfo信息获取activityInfo信息
        -> stack.mConfigWillChange:log打印debug:Starting activity when config will change = false 
        -> startActivity-585:指明calling是谁,intent,resolveinfo这些信息
            -> startActivity-626:创建ActivityRecord为mStartActivity
                -> mSupervisor.getActivityMetricsLogger().notifyActivityLaunching:log打印debug:notifyActivityLaunching: active:false, intent:Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] }
                -> log打印:START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552]} from uid 10081
                -> log打印debug:Will send result to Token{c133fda ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}} ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}
                -> new ActivityRecord:创建activityRecord
                    -> setState:log打印debug:State movement: ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t-1} from:null to:INITIALIZING reason:ActivityRecord ctor
                -> startActivity-1396:先推迟布局传递;启动activity;然后恢复布局传递
                    -> mService.mWindowManager.deferSurfaceLayout():推迟布局传递;
                    -> startActivityUnchecked:创建activitystack和taskrecord
                        -> setInitialState:log打印debug:startActivity() => mUserLeaving=true
                        -> getReusableIntentActivity
                            -> mRootActivityContainer.findTask
                                -> log打印debug:Looking for task of ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t-1}
                                -> preferredDisplay.findTaskLocked
                                    -> stack.findTaskLocked
                                        -> log打印debug:Looking for task of ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t-1} in ActivityStack{c5165f7 stackId=0 type=home mode=fullscreen visible=true translucent=false, 1 tasks}
                                        -> log打印debug:Comparing existing cls=com.android.launcher3/.Launcher/aff=null to new cls=com.android.gallery3d/.app.GalleryActivity/aff=com.android.gallery3d
                                        -> log打印debug:Not a match: TaskRecord{4a49afc #38 ?? U=0 StackId=0 sz=1}
                                -> log打印debug:No task found
                        -> setTaskFromReuseOrCreateNewTask:创建activitystack和taskrecord
                            -> computeStackFocus:创建activitystack
                                -> getLaunchStack
                                    -> mRootActivityContainer.getLaunchStack
                                        -> ActivityDisplay类:display.getOrCreateStack
                                            -> createStack
                                                -> createStackUnchecked
                                                    -> new ActivityStack
                                                        -> display.addChild:log打印debug:addChild: attaching ActivityStack{4f312fa stackId=3 type=standard mode=fullscreen visible=false translucent=true, 0 tasks} to displayId=0 position=1
                            -> mSupervisor.getNextTaskIdForUserLocked
                                -> mRootActivityContainer.anyTaskForId
                                    -> log打印debug:Looking for task id=41 in recents
                                    -> log打印debug:Didn't find task id=41 in recents
                            -> mTargetStack.createTaskRecord:创建taskrecord
                                -> ActivityStack类:TaskRecord.create
                                    -> getTaskRecordFactory().create
                                        -> new TaskRecord
                                            -> setIntent:log打印debug:Setting Intent of TaskRecord{2a370ab #41 A=com.android.gallery3d U=0 StackId=-1 sz=0} to Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity }
                                -> addTask
                            -> addOrReparentStartingActivity
                                -> parent.addActivityToTop
                                    -> addActivityAtIndex
                                        -> updateEffectiveIntent
                                            -> setIntent
                                                -> setLockTaskAuth:log打印debug:setLockTaskAuth: task=TaskRecord{2a370ab #41 A=com.android.gallery3d U=0 StackId=3 sz=1} mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE
                            -> log打印debug:Starting new activity ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t41} in new task TaskRecord{2a370ab #41 A=com.android.gallery3d U=0 StackId=3 sz=1}
                            -> mTargetStack.moveToFront
                                -> display.positionChildAtTop
                                    -> positionChildAt
                                        -> mDisplayContent.positionStackAt
                                            -> mTaskStackContainers.positionChildAt
                                                -> mRootActivityContainer.onChildPositionChanged
                                                    -> positionChildAt
                                                        -> mStackSupervisor.updateTopResumedActivityIfNeeded
                                                            -> prevTopActivity.scheduleTopResumedActivityChanged:activity为launcher
                                                                -> log打印debug:Sending position change to ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}, onTop: false
                                                                -> mAtmService.getLifecycleManager().scheduleTransaction:(1. Launcher3:Launcher3的onTop状态转换,TopResumedActivityChangeItem类)
                                                                    -> transaction.schedule
                                                                        -> mClient.scheduleTransaction(Launcher3)	
                                                            -> scheduleTopResumedStateLossTimeout:log打印debug:Waiting for top state to be released by ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}
                        -> mTargetStack.startActivityLocked:启动动画和启动窗口的工作(WMS相关)
                            -> ActivityStack类:insertTaskAtTop:将taskrecord到mTaskHistory中
                            -> log打印debug:Adding activity 
                            -> r.createAppWindowToken:创建AppWindowToken
                                -> addActivityToTop
                                    -> addActivityAtIndex
                                        -> updateEffectiveIntent
                                            -> setIntent
                                                -> setLockTaskAuth:log打印debug:setLockTaskAuth: task=TaskRecord{2a370ab #41 A=com.android.gallery3d U=0 StackId=3 sz=1} mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE
                            -> log打印debug:Prepare open transition: starting ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t41}
                            -> dc.prepareAppTransition:准备应用的动画
                            -> r.showStartingWindow:调用WMS创建窗口相关的
                        -> mRootActivityContainer.resumeFocusedStacksTopActivities
                            -> targetStack.resumeTopActivityUncheckedLocked
                                -> ActivityStack类:resumeTopActivityInnerLocked
                                    -> log打印debug:Resuming ActivityRecord{573a125 u0 com.android.gallery3d/.app.GalleryActivity t41}
                                    -> getDisplay().pauseBackStacks
                                        -> log打印debug:pauseBackStacks: stack=ActivityStack{c5165f7 stackId=0 type=home mode=fullscreen visible=true translucent=false, 1 tasks} mResumedActivity=ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}
                                        -> stack.startPausingLocked
                                            -> log打印debug:Moving to PAUSING: ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}
                                            -> prev.setState
                                                -> parent.onActivityStateChanged
                                                    -> setResumedActivity
                                                        -> log打印debug:setResumedActivity stack:ActivityStack{c5165f7 stackId=0 type=home mode=fullscreen visible=true translucent=false, 1 tasks} + from: ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38} to:null reason:startPausingLocked - onActivityStateChanged
                                            -> log打印debug:Enqueueing pending pause: ActivityRecord{3ca1fef u0 com.android.launcher3/.Launcher t38}
                                            -> mService.getLifecycleManager().scheduleTransaction(2. Launcher3:Launcher3变为onPause状态,PauseActivityItem类)
                                                -> transaction.schedule
                                                    -> mClient.scheduleTransaction(Launcher3)
                                                        -> TransactionExecutor类:lifecycleItem.postExecute(异步进行的)	
                                                            -> ActivityTaskManager.getService().activityPaused(token)
                                                                -> stack.activityPausedLocked:log打印debug:Activity paused: token=Token{7aafab ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2}}, timeout=false
                                                                -> mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r):去掉PAUSE_TIMEOUT_MSG消息
                                                                -> log打印debug:Moving to PAUSED: ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2} (pause complete)
                                                                -> completePauseLocked
                                                                    -> log打印debug:Complete pause: ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2}
                                                                    -> prev.setState(PAUSED, "completePausedLocked")
                                                                        -> log打印debug:State movement: ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2} from:PAUSING to:PAUSED reason:completePausedLocked
                                                                    -> log打印debug:Enqueue pending stop if needed: ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2} wasStopping=false visible=true
                                                                    -> mRootActivityContainer.resumeFocusedStacksTopActivities
                                                                        -> targetStack.resumeTopActivityUncheckedLocked
                                                                            -> resumeTopActivityInnerLocked
                                                                                -> log打印debug:Resuming ActivityRecord{3228943 u0 com.android.gallery3d/.app.GalleryActivity t3}
                                                                                -> log打印debug:Prepare open transition: prev=ActivityRecord{31fc7b5 u0 com.android.launcher3/.Launcher t2}
                                                                                -> dc.prepareAppTransition(prev.getTaskRecord() == next.getTaskRecord() ? TRANSIT_ACTIVITY_OPEN: next.mLaunchTaskBehind ? TRANSIT_TASK_OPEN_BEHIND: TRANSIT_TASK_OPEN, false)
                                                                                -> next.applyOptionsLocked
                                                                                    -> log打印debug:Applying options for ActivityRecord{3228943 u0 com.android.gallery3d/.app.GalleryActivity t3}
                                                                                -> log打印debug:resumeTopActivityLocked: Restarting ActivityRecord{3228943 u0 com.android.gallery3d/.app.GalleryActivity t3}
                                                                                -> mStackSupervisor.startSpecificActivityLocked(启动gallery3d,异步的)
                                                                                    -> PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent())
                                                                                        -> ActivityManagerService类:startProcess(给zygote发消息,创建应用进程)
                                                                                            -> startProcessLocked
                                                                                                -> mProcessList.startProcessLocked
                                                                                                    -> log打印debug:Clearing bad process: 10096/com.android.gallery3d
                                                                                                    -> log打印debug:startProcess: name=com.android.gallery3d app=null knownToBeDead=false thread=null pid=-1
                                                                                                    -> newProcessRecordLocked:创建processrecord	
                                                                                                        -> new ProcessRecord
                                                                                                        -> addProcessNameLocked
                                                                                                            -> new UidRecord
                                                                                                            -> log打印debug:Creating new process uid: UidRecord{da981 u0a96 CEM  idle procs:0 seq(0,0,0)}
                                                                                                            -> mProcessNames.put(proc.processName, proc.uid, proc)
                                                                                                        -> startProcessLocked
                                                                                                            -> 准备好参数:startProcessLocked
                                                                                                                -> log打印debug:Posting procStart msg for 0:com.android.gallery3d/u0a96
                                                                                                                    -> mService.mProcStartHandler.post
                                                                                                                        -> startProcess:向zygote的socket发送消息
                                                                                                                            -> Process.start
                                                                                                                                -> ZYGOTE_PROCESS.start
                                                                                                                                    -> startViaZygote
                                                                                                                                        -> zygoteSendArgsAndGetResult(1. gallery3d:给zygote的socket发消息)
                                                                                                                                            -> msgStr:14 --runtime-args --setuid=10096 --setgid=10096 --runtime-flags=10240 --mount-external-write --target-sdk-version=28 --setgroups=50096,20096,9997,3003 --nice-name=com.android.gallery3d --seinfo=default:targetSdkVersion=28:complete --instruction-set=x86 --app-data-dir=/data/user/0/com.android.gallery3d --package-name=com.android.gallery3d android.app.ActivityThread seq=39
                                                                                                                                            -> attemptZygoteSendArgsAndGetResult:将msgStr的信息通过zygote socket发送给zygote
                                                                                                                        -> handleProcessStartedLocked
                                                                                                                            -> log打印:Start proc 3471:com.android.gallery3d/u0a96 for activity {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}
                                                                                                                            -> 发送PROC_START_TIMEOUT_MSG消息:10秒钟,启动进程超时
                                                                    -> mRootActivityContainer.ensureActivitiesVisible
                                                                        -> display.ensureActivitiesVisible
                                                                            -> stack.ensureActivitiesVisibleLocked(循环中gallery3d应用的)
                                                                                -> log打印debug:ensureActivitiesVisible behind ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} configChanges=0x0
                                                                                -> updateBehindFullscreen
                                                                                    -> log打印debug:Fullscreen: at ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} stackInvisible=false behindFullscreenActivity=false
                                                                                -> log打印debug:Make visible? ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} finishing=false state=INITIALIZING
                                                                                -> r.ensureActivityConfiguration
                                                                                    -> log打印debug:Ensuring correct configuration: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                                                    -> log打印debug:Skipping config check for initializing activity: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                                                -> makeVisibleAndRestartIfNeeded
                                                                                    -> log打印debug:Start and freeze screen for ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                                                    -> r.startFreezingScreenLocked
                                                                                    -> log打印debug:Starting and making visible: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                                                    -> r.setVisible(true)
                                                                                    -> mStackSupervisor.startSpecificActivityLocked(这里也调用ActivityManagerInternal::startProcess,不过在ProcessList.startProcessLocked就立刻返回了)
                                                                                        -> PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent())
                                                                            -> stack.ensureActivitiesVisibleLocked(循环中launcher3应用的)
                                                                                -> log打印debug:ensureActivitiesVisible behind ActivityRecord{af4fd4e u0 com.android.launcher3/.Launcher t6} configChanges=0x0
                                                                                -> log打印debug:Make invisible? ActivityRecord{af4fd4e u0 com.android.launcher3/.Launcher t6} finishing=false state=PAUSED stackShouldBeVisible=false behindFullscreenActivity=true mLaunchTaskBehind=false
                                                                                -> makeInvisible
                                                                                    -> log打印debug:Making invisible: ActivityRecord{af4fd4e u0 com.android.launcher3/.Launcher t6} PAUSED
                                                                                    -> addToStopping
                                                                                        -> log打印debug:Scheduling idle now: forceIdle=trueimmediate=true
                                                                                        -> mStackSupervisor.scheduleIdleLocked
                                                                                            -> 发送IDLE_NOW_MSG消息
                                                                                                -> log打印debug:handleMessage: IDLE_NOW_MSG: r=null
                                                                                                    -> activityIdleInternal
                                                                                                        -> mRootActivityContainer.allResumedActivitiesIdle
                                                                                                            -> log打印debug:allResumedActivitiesIdle: stack=1 null not idle
                                                                                                            -> processStoppingActivitiesLocked
                                                                                                                -> log打印debug:Stopping ActivityRecord{af4fd4e u0 com.android.launcher3/.Launcher t6}: nowVisible=false animating=true finishing=false
                                                                                                            -> mService.mH.post(() -> mService.mAmInternal.trimApplications()):更新应用的分数
                                                                                                                -> trimApplicationsLocked
                                                                                                                    -> updateOomAdjLocked
                                                                                                                        -> mOomAdjuster.updateOomAdjLocked
                                                                                                                            -> computeOomAdjLocked
                                                                                                                                -> log打印debug:Making empty: ProcessRecord{1f18dda 2621:com.android.launcher3/u0a81}
                                                                                                                            -> applyOomAdjLocked
                                                                                -> log打印debug:Home task: at TaskRecord{a14e77c #6 ?? U=0 StackId=0 sz=1} stackShouldBeVisible=false behindFullscreenActivity=true
                                            -> schedulePauseTimeout
                                                -> 发送PAUSE_TIMEOUT_MSG消息,500ms延时
                                                -> log打印debug:Waiting for pause to complete...
                    -> mService.mWindowManager.continueSurfaceLayout:开始显示窗口了
                    -> postStartActivityProcessing
                        -> mSupervisor.reportWaitingActivityLaunchedIfNeeded:调用startActivityMayWait回调通知
        -> startActivity结束了
        
        

1.2 launcher3-startactivity

(1)Launcher3的onTop状态转换
prevTopActivity.scheduleTopResumedActivityChanged:
    -> ActivityThread类:ActivityThread.this.scheduleTransaction
        -> 发送EXECUTE_TRANSACTION消息:log打印debug:SCHEDULE 159 EXECUTE_TRANSACTION: 0 / android.app.servertransaction.ClientTransaction@8363
            -> handleMessage:log打印debug:>>> handling: EXECUTE_TRANSACTION
                -> mTransactionExecutor.execute
                    -> log打印debug:tId:33635 Start resolving transaction
                    -> log打印debug:
                        tId:33635 ClientTransaction{	
                        tId:33635   callbacks=[
                        tId:33635     TopResumedActivityChangeItem{onTop=false}
                        tId:33635   ]
                        tId:33635   stateRequest=null
                        tId:33635 }
                        tId:33635 Target activity: com.android.launcher3.Launcher
                    -> executeCallbacks
                        -> log打印debug:tId:33635 Resolving callbacks in transaction
                        -> log打印debug:tId:33635 Resolving callback: TopResumedActivityChangeItem{onTop=false}
                        -> item.execute
                            -> TopResumedActivityChangeItem类:client.handleTopResumedActivityChanged(client为ActivityThread)
                                -> log打印debug:Received position change to top: false for activity: ActivityRecord{c1dccc9 token=android.os.BinderProxy@a712c93 {com.android.launcher3/com.android.launcher3.Launcher}}
                                -> ActivitThread类:r.isTopResumedActivity = onTop;
                        -> item.postExecute
                            -> ActivityTaskManager.getService().activityTopResumedStateLost
                                -> mStackSupervisor.handleTopResumedStateReleased
                                    -> log打印debug:Top resumed state released  (transition complete)
                                    -> mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG):对应scheduleTopResumedStateLossTimeout
                    -> log打印debug:tId:33635 End resolving transaction
            -> log打印debug:<<< done: EXECUTE_TRANSACTION
        
(2)Launcher3变为onPause状态
mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(), prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, prev.configChangeFlags, pauseImmediately)):
    -> ActivityThread类:ActivityThread.this.scheduleTransaction
        -> 发送EXECUTE_TRANSACTION消息:log打印debug:SCHEDULE 159 EXECUTE_TRANSACTION: 0 / android.app.servertransaction.ClientTransaction@efd342
            -> handleMessage:log打印debug:>>> handling: EXECUTE_TRANSACTION
                -> mTransactionExecutor.execute
                    -> log打印debug:tId:15717186 Start resolving transaction
                    -> log打印debug:
                        tId:15717186 ClientTransaction{
                        tId:15717186   callbacks=[]
                        tId:15717186   stateRequest=PauseActivityItem{finished=false,userLeaving=true,configChanges=0,dontReport=false}
                        tId:15717186 }
                        tId:15717186 Target activity: com.android.launcher3.Launcher
                    -> executeLifecycleState
                        -> log打印debug:tId:15717186 Resolving lifecycle state: PauseActivityItem{finished=false,userLeaving=true,configChanges=0,dontReport=false} for activity: .Launcher
                        -> cycleToPath
                            -> log打印debug:tId:15717186 Cycle activity: .Launcher from: ON_RESUME to: ON_PAUSE excludeLastState: true
                        -> lifecycleItem.execute(这个lifecycleItem为PauseActivityItem)
                            -> PauseActivityItem类:client.handlePauseActivity
                                -> ActivityThread类:performPauseActivity
                                    -> performPauseActivityIfNeeded
                                        -> mInstrumentation.callActivityOnPause
                                            -> activity.performPause
                                                -> Launcher类:onPause
                                                    -> BaseActivity类:onPause
                                                        -> Activity类:onPause
                                                            -> log打印debug:onPause com.android.launcher3.Launcher@fc5eada
                        -> lifecycleItem.postExecute
                            -> ActivityTaskManager.getService().activityPaused(token)
                    -> log打印debug:tId:15717186 End resolving transaction
            -> log打印debug:<<< done: EXECUTE_TRANSACTION
                        
(3)Launcher3变为onStop状态		
        

1.3 gallery3d-startactivity

(1)gallery3d:给zygote的socket发消息
参数:msgStr:14 --runtime-args --setuid=10096 --setgid=10096 --runtime-flags=10240 --mount-external-write --target-sdk-version=28 --setgroups=50096,20096,9997,3003 --nice-name=com.android.gallery3d --seinfo=default:targetSdkVersion=28:complete --instruction-set=x86 --app-data-dir=/data/user/0/com.android.gallery3d --package-name=com.android.gallery3d android.app.ActivityThread seq=39

ZygoteInit类:main
    -> zygoteServer.runSelectLoop
        -> connection.processOneCommand
            -> Zygote.forkAndSpecialize
                -> nativeForkAndSpecialize
                    -> com_android_internal_os_Zygote_nativeForkAndSpecialize
                        -> ForkCommon
                            -> fork
                            -> log打印:Forked child process 3471
                        -> SpecializeCommon:根据传进来的参数设置进程属性
            -> handleChildProc
                -> return ZygoteInit.zygoteInit:返回ZygoteInit对象
                    -> RuntimeInit.applicationInit
                        -> findStaticMain:找android.app.ActivityThread的main函数
    -> caller.run
        -> ActivityThread类:main
            -> new ActivityThread:新建activitythread对象
            -> thread.attach
                -> mgr.attachApplication
                    -> ActivityManagerService类:attachApplicationLocked
                        -> log打印debug:Binding process pid 3471 to record ProcessRecord{d24bc14 3471:com.android.gallery3d/u0a96}
                        -> new AppDeathRecipient
                            -> log打印debug:New death recipient com.android.server.am.ActivityManagerService$AppDeathRecipient@5838b5f for thread android.os.BinderProxy@7f379ac
                        -> log打印debug:New app record ProcessRecord{d24bc14 3471:com.android.gallery3d/u0a96} thread=android.os.BinderProxy@7f379ac pid=3471
                        -> log打印debug:Binding proc com.android.gallery3d with config {1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.6}
                        -> thread.bindApplication(gallery3d应用进程中)
                            -> ActivityThread类:发送BIND_APPLICATION消息 
                                -> handleBindApplication(1. bindapplication重点,消息的形式,为异步的)
                                    -> android.ddm.DdmHandleAppName.setAppName:这里才可以在debugger中看到com.android.gallery3d名字
                        -> mProcessList.updateLruProcessLocked
                            -> log打印debug:Adding at 26 of LRU list: ProcessRecord{d24bc14 3471:com.android.gallery3d/u0a96}
                        -> mAtmInternal.attachApplication
                            -> mRootActivityContainer.attachApplication
                                -> mStackSupervisor.realStartActivityLocked
                                    -> mRootActivityContainer.ensureVisibilityAndConfig
                                        -> ensureActivitiesVisible
                                            -> display.ensureActivitiesVisible
                                                -> stack.ensureActivitiesVisibleLocked(看gallery3d是否设为Visible了,launcher3设为invisible了,见activity_call.txt中的log打印)
                                        -> mService.updateDisplayOverrideConfigurationLocked
                                            -> ensureConfigAndVisibilityAfterUpdate
                                                -> starting.ensureActivityConfiguration
                                                    -> log打印debug:Ensuring correct configuration: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                    -> log打印debug:Configuration & display unchanged in ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                                -> mRootActivityContainer.ensureActivitiesVisible
                                                    -> display.ensureActivitiesVisible
                                                        -> stack.ensureActivitiesVisibleLocked(看gallery3d是否设为Visible了,launcher3设为invisible了,见activity_call.txt中的log打印)
                                    -> r.setVisibility(true)
                                    -> log打印debug:Launching: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}
                                    -> log打印debug:Launching: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} icicle=null with results=null newIntents=null andResume=true
                                    -> clientTransaction.addCallback(LaunchActivityItem.obtain):添加LaunchActivityItem
                                    -> clientTransaction.setLifecycleStateRequest(lifecycleItem):设置ResumeActivityItem
                                    -> mService.getLifecycleManager().scheduleTransaction(clientTransaction):先执行LaunchActivityItem,然后执行ResumeActivityItem(异步的形式)
                                        -> transaction.schedule
                                            -> mClient.scheduleTransaction(gallery3d)
                                    -> stack.minimalResumeActivityLocked:log打印debug:Moving to RESUMED: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} (starting new instance) callers=com.android.server.wm.ActivityStackSupervisor.realStartActivityLocked:917 com.android.server.wm.RootActivityContainer.attachApplication:784 com.android.server.wm.ActivityTaskManagerService$LocalService.attachApplication:6889 com.android.server.am.ActivityManagerService.attachApplicationLocked:5103 com.android.server.am.ActivityManagerService.attachApplication:5180 
                                        -> r.setState
                                            -> log打印debug:State movement: ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} from:INITIALIZING to:RESUMED reason:minimalResumeActivityLocked
                                            -> parent.onActivityStateChanged
                                                -> log打印debug:set resumed activity to:ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} reason:minimalResumeActivityLocked
                                                -> setResumedActivity
                                                    -> log打印debug:setResumedActivity stack:ActivityStack{e8f3fd8 stackId=1 type=standard mode=fullscreen visible=true translucent=false, 1 tasks} + from: null to:ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7} reason:minimalResumeActivityLocked - onActivityStateChanged
                                                    -> mStackSupervisor.updateTopResumedActivityIfNeeded
                                                        -> scheduleTopResumedActivityStateIfNeeded
                                                            -> mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */):设置onTop为True
                                                                -> log打印debug:Sending position change to ActivityRecord{daf1ebb u0 com.android.gallery3d/.app.GalleryActivity t7}, onTop: true
                                                                -> mAtmService.getLifecycleManager().scheduleTransaction:调度TopResumedActivityChangeItem
                                                -> mStackSupervisor.mRecentTasks.add:加到最近task列表中
                                                    -> log打印debug:add: task=TaskRecord{1822f31 #7 A=com.android.gallery3d U=0 StackId=1 sz=1}
                                                    -> log打印debug:addRecent: trimming tasks for TaskRecord{1822f31 #7 A=com.android.gallery3d U=0 StackId=1 sz=1}
                                                
                

(2)处理BIND_APPLICATION消息:加载应用的jar包
ActivityManagerService类:attachApplicationLocked
    -> thread.bindApplication
        -> ActivityThread类:发送BIND_APPLICATION消息
            -> handleBindApplication(data)
                -> Process.setArgV0(data.processName):这里才可以在debugger中看到com.android.gallery3d名字
                -> VMRuntime.setProcessDataDirectory(data.appInfo.dataDir):设置data目录
                -> getPackageInfoNoCheck(data.appInfo, data.compatInfo):获取LoadedApk对象
                    -> getPackageInfo
                        -> log打印debug:Loading code package com.android.gallery3d (in com.android.gallery3d)
                        -> new LoadedApk
                -> ContextImpl.createAppContext:创建ContextImpl上下文
                -> data.info.makeApplication:此处data.info是指LoadedApk, 通过反射创建目标应用Application对象
                    -> getClassLoader:创建ClassLoader对象
                        -> createOrUpdateClassLoaderLocked
                            -> 如果包名为android,则加载systemclassloader
                            -> 如果包名不为android,ActivityManager.getService().addPackageDependency
                            -> makePaths:设置库的路径,如/vendor/lib和/system/lib等
                            -> 加载JNI库等
                            -> 创建classloader
                    -> mActivityThread.mInstrumentation.newApplication:创建Application对象
                        -> app.attach
                    -> instrumentation.callApplicationOnCreate
                        -> app.onCreate:调用Application类的onCreate函数
                -> installContentProviders:加载providers
                    -> log打印debug:Pub com.android.gallery3d.provider: com.android.gallery3d.provider.GalleryProvider
                    -> installProvider
                        -> log打印debug:Loading provider com.android.gallery3d.provider: com.android.gallery3d.provider.GalleryProvider
                        -> log打印debug:Instantiating local provider com.android.gallery3d.provider.GalleryProvider
                        -> localProvider.attachInfo
                        -> log打印debug:Checking to add android.content.ContentProvider$Transport@22aa7b1 / com.android.gallery3d.provider.GalleryProvider
                        -> provider.asBinder
            
                
(3)运行LaunchActivityItem和ResumeActivityItem
mService.getLifecycleManager().scheduleTransaction:
    -> ActivityThread类:ActivityThread.this.scheduleTransaction
        -> 发送EXECUTE_TRANSACTION消息:log打印debug:SCHEDULE 159 EXECUTE_TRANSACTION: 0 / android.app.servertransaction.ClientTransaction@8382
            -> handleMessage:log打印debug:>>> handling: EXECUTE_TRANSACTION
                -> mTransactionExecutor.execute
                    -> log打印debug:tId:-1526643507 Start resolving transaction
                    -> log打印debug:
                        tId:-1526643507 ClientTransaction{
                        tId:-1526643507   callbacks=[
                        tId:-1526643507     LaunchActivityItem{intent=Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] },ident=229580475,info=ActivityInfo{910ded com.android.gallery3d.app.GalleryActivity},curConfig={1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.6},overrideConfig={1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1},referrer=com.android.launcher3,procState=21,state=null,persistentState=null,pendingResults=null,pendingNewIntents=null,profilerInfo=null assistToken=android.os.BinderProxy@c244a58}
                        tId:-1526643507   ]
                        tId:-1526643507   stateRequest=ResumeActivityItem{procState=-1,updateProcState=false,isForward=true}
                        tId:-1526643507 }
                        tId:-1526643507 Target activity: Not found for token: android.os.BinderProxy@3bfb404
                    -> executeCallbacks
                        -> log打印debug:tId:-1526643507 Resolving callbacks in transaction
                        -> log打印debug:tId:-1526643507 Resolving callback: LaunchActivityItem{intent=Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] },ident=229580475,info=ActivityInfo{910ded com.android.gallery3d.app.GalleryActivity},curConfig={1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.6},overrideConfig={1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1},referrer=com.android.launcher3,procState=21,state=null,persistentState=null,pendingResults=null,pendingNewIntents=null,profilerInfo=null assistToken=android.os.BinderProxy@c244a58}
                        -> item.execute
                            -> client.handleLaunchActivity
                                -> handleConfigurationChanged
                                    -> log打印debug:Handle configuration changed: {1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.6}
                                    -> mResourcesManager.applyConfigurationToResourcesLocked
                                        -> log打印debug:Skipping new config: curSeq=6, newSeq=6
                                -> log打印debug:Handling launch of ActivityRecord{24f5422 token=android.os.BinderProxy@3bfb404 {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}}
                                -> WindowManagerGlobal.initialize:初始化windows
                                -> performLaunchActivity
                                    -> log打印debug:Performing launch of ActivityRecord{24f5422 token=android.os.BinderProxy@3bfb404 {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}}
                                    -> log打印debug:ActivityRecord{24f5422 token=android.os.BinderProxy@3bfb404 {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}}: app=com.android.gallery3d.app.GalleryAppImpl@860c70, appName=com.android.gallery3d, pkg=com.android.gallery3d, comp={com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}, dir=/system/product/app/Gallery2/Gallery2.apk
                                    -> log打印debug:Launching activity com.android.gallery3d.app.GalleryActivity with config {1.0 310mcc260mnc [en_US] ldltr sw320dp w320dp h461dp 240dpi nrml port finger qwerty/v/v tball/v winConfig={ mBounds=Rect(0, 0 - 480, 800) mAppBounds=Rect(0, 0 - 480, 728) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1}
                                    -> activity.attach:创建window窗口相关了
                                        -> new PhoneWindow
                                        -> mWindow.setWindowManager
                                    -> mInstrumentation.callActivityOnCreate
                                        -> activity.performCreate
                                            -> onCreate
                                                -> log打印debug:onCreate com.android.gallery3d.app.GalleryActivity@a177f9c: null
                                    -> r.setState(ON_CREATE)
                        -> item.postExecute
                    -> executeLifecycleState
                        -> log打印debug:tId:-1526643507 Resolving lifecycle state: ResumeActivityItem{procState=-1,updateProcState=false,isForward=true} for activity: .app.GalleryActivity
                        -> cycleToPath
                            -> log打印debug:tId:-1526643507 Cycle activity: .app.GalleryActivity from: ON_CREATE to: ON_RESUME excludeLastState: true
                            -> performLifecycleSequence
                                -> tId:-1526643507 Transitioning activity: .app.GalleryActivity to state: ON_START
                                -> mTransactionHandler.handleStartActivity
                                    -> activity.performStart
                                        -> mInstrumentation.callActivityOnStart
                                            -> activity.onStart
                                                -> log打印debug:onStart com.android.gallery3d.app.GalleryActivity@a177f9c
                        -> lifecycleItem.execute(这个lifecycleItem为ResumeActivityItem)
                            -> client.handleResumeActivity
                                -> performResumeActivity
                                    -> log打印debug:Performing resume of ActivityRecord{24f5422 token=android.os.BinderProxy@3bfb404 {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}} finished=false
                                    -> r.activity.performResume
                                        -> mInstrumentation.callActivityOnResume
                                            -> activity.onResume
                                                -> log打印debug:onResume com.android.gallery3d.app.GalleryActivity@a177f9c
                        -> lifecycleItem.postExecute
                            -> ActivityTaskManager.getService().activityPaused(token)
                    -> log打印debug:tId:15717186 End resolving transaction
            -> log打印debug:<<< done: EXECUTE_TRANSACTION

(4)gallery3d:的onTop状态转换,转为true
mTopResumedActivity.scheduleTopResumedActivityChanged(true /* onTop */):
    -> ActivityThread类:ActivityThread.this.scheduleTransaction
        -> 发送EXECUTE_TRANSACTION消息:log打印debug:SCHEDULE 159 EXECUTE_TRANSACTION: 0 / android.app.servertransaction.ClientTransaction@8363
            -> handleMessage:log打印debug:>>> handling: EXECUTE_TRANSACTION
                -> mTransactionExecutor.execute
                    -> log打印debug:tId:33666 Start resolving transaction
                    -> log打印debug:
                        tId:33666 ClientTransaction{	
                        tId:33666   callbacks=[
                        tId:33666     TopResumedActivityChangeItem{onTop=true}
                        tId:33666   ]
                        tId:33666   stateRequest=null
                        tId:33666 }
                        tId:33666 Target activity: com.android.gallery3d.app.GalleryActivity
                    -> executeCallbacks
                        -> log打印debug:tId:33666 Resolving callbacks in transaction
                        -> log打印debug:tId:33666 Resolving callback: TopResumedActivityChangeItem{onTop=true}
                        -> item.execute
                            -> TopResumedActivityChangeItem类:client.handleTopResumedActivityChanged(client为ActivityThread)
                                -> log打印debug:Received position change to top: true for activity: ActivityRecord{24f5422 token=android.os.BinderProxy@3bfb404 {com.android.gallery3d/com.android.gallery3d.app.GalleryActivity}}
                                -> ActivitThread类:r.isTopResumedActivity = onTop;
                        -> item.postExecute
                            -> ActivityTaskManager.getService().activityTopResumedStateLost
                                -> mStackSupervisor.handleTopResumedStateReleased
                                    -> log打印debug:Top resumed state released  (transition complete)
                                    -> mHandler.removeMessages(TOP_RESUMED_STATE_LOSS_TIMEOUT_MSG):对应scheduleTopResumedStateLossTimeout
                    -> log打印debug:tId:33666 End resolving transaction
            -> log打印debug:<<< done: EXECUTE_TRANSACTION

2. 应用状态的变化

ATMS:startActivity
    -> ActivityStarter类:startActivityMayWait
        -> resolveIntent:调用PMS,根据intent来获取resolveInfo信息,也就是manifest.xml中的信息
        -> resolveActivity:根据resolveInfo信息获取activityInfo信息
        -> startActivity
            -> new ActivityRecord:创建activityRecord
                -> gallery3d状态:from:null to:INITIALIZING
            -> startActivity
                -> startActivityUnchecked
                    -> setTaskFromReuseOrCreateNewTask:创建activitystack和taskrecord
                        -> computeStackFocus:创建activitystack
                        -> mTargetStack.createTaskRecord:创建taskrecord
                        -> mTargetStack.moveToFront
                            -> prevTopActivity.scheduleTopResumedActivityChanged
                                -> launcher3状态:onTop: false
                    -> mTargetStack.startActivityLocked:启动动画和启动窗口的工作(WMS相关)
                    -> mRootActivityContainer.resumeFocusedStacksTopActivities
                        -> stack.startPausingLocked
                            -> launcher3状态:ON_RESUME to: ON_PAUSE
                                -> 回调:ActivityTaskManager.getService().activityPaused
                                    -> launcher3状态:from:PAUSING to:PAUSED
                                    -> mRootActivityContainer.resumeFocusedStacksTopActivities
                                        -> mStackSupervisor.startSpecificActivityLocked
                                            -> ActivityManagerInternal::startProcess:给zygote发消息,创建gallery3d应用
                                                -> gallery3d应用:ActivityThread类:main
                                                    -> new ActivityThread:新建activitythread对象
                                                        -> mgr.attachApplication
                                                            -> thread.bindApplication:获取LoadedApk对象和创建ContextImpl和创建Application对象
                                                            -> mAtmInternal.attachApplication
                                                                -> mStackSupervisor.realStartActivityLocked
                                                                    -> clientTransaction.addCallback(LaunchActivityItem.obtain):添加LaunchActivityItem(异步)
                                                                        -> 	performLaunchActivity
                                                                            -> activity.attach
                                                                                -> new PhoneWindow
                                                                                -> mWindow.setWindowManager
                                                                            -> mInstrumentation.callActivityOnCreate
                                                                                -> onCreate
                                                                    -> clientTransaction.setLifecycleStateRequest(lifecycleItem):设置ResumeActivityItem(异步)
                                                                        -> mInstrumentation.callActivityOnStart
                                                                            -> activity.onStart
                                                                        -> performResumeActivity
                                                                            -> activity.onResume
                                                                    -> stack.minimalResumeActivityLocked
                                                                        -> gallery3d状态:from:INITIALIZING to:RESUMED

源码解析

framework层

1. ActivityTaskManagerService类

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

1.1 startActivity-1006行-启动应用

    @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,
                                   // 这里,加多了个userId
                UserHandle.getCallingUserId());
    }

1.2 startActivityAsUser-1029行-启动应用-多了个validateIncomingUser

    @Override
    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                                   // 这里加了个,验证传入用户
                true /*validateIncomingUser*/);
    }

1.3 startActivityAsUser-调用activitystart来启动应用-从哪里来启动谁

startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);      
// caller:launcher的application thread
// callingPackage:com.android.launcher3;
// intent:Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] }
// resolvedType:null;resultTo:Token{e581a9b ActivityRecord{9a96eaa u0 com.android.launcher3/.Launcher t144}}
// resultWho:null;requestCode:-1;startFlags:0;profilerInfo:null;
// bOptions:Bundle[mParcelledData.dataSize=276];userId:0;validateIncomingUser:true;
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("startActivityAsUser");

        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

        // TODO: Switch to user app stacks here.
    // ActivityStartController类
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();

    }

1.4 initialize-ATMS服务初始化

// AMS构造函数调用这个函数:mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());    
public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
            Looper looper) {
        mH = new H(looper);	// DisplayThread
        mUiHandler = new UiHandler();
        mIntentFirewall = intentFirewall;
        final File systemDir = SystemServiceManager.ensureSystemDir();
        mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
        mCompatModePackages = new CompatModePackages(this, systemDir, mH);
        mPendingIntentController = intentController;

        mTempConfig.setToDefaults();
        mTempConfig.setLocales(LocaleList.getDefault());
        mConfigurationSeq = mTempConfig.seq = 1;
        mStackSupervisor = createStackSupervisor();
        mRootActivityContainer = new RootActivityContainer(this);
        mRootActivityContainer.onConfigurationChanged(mTempConfig);

        mTaskChangeNotificationController =
                new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
        mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
        mActivityStartController = new ActivityStartController(this);
        mRecentTasks = createRecentTasks();
        mStackSupervisor.setRecentTasks(mRecentTasks);
        mVrController = new VrController(mGlobalLock);
        mKeyguardController = mStackSupervisor.getKeyguardController();
    }

1.5 getProcessController-获取WindowProcessController

    WindowProcessController getProcessController(IApplicationThread thread) {
        if (thread == null) {
            return null;
        }

        final IBinder threadBinder = thread.asBinder();
        // mProcessNames保存
        final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
        for (int i = pmap.size()-1; i >= 0; i--) {
            final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
            for (int j = procs.size() - 1; j >= 0; j--) {
                final WindowProcessController proc = procs.valueAt(j);
                // 遍历相等
                if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
                    return proc;
                }
            }
        }

        return null;
    }

2. ActivityStartController类

frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java

ActivityStartController类是用来控制ActivityStarter对象的生成的

2.1 ActivityStartController构造函数

    ActivityStartController(ActivityTaskManagerService service) {
        this(service, service.mStackSupervisor,
                new DefaultFactory(service, service.mStackSupervisor,
                    new ActivityStartInterceptor(service, service.mStackSupervisor)));
    }

    @VisibleForTesting
    ActivityStartController(ActivityTaskManagerService service, ActivityStackSupervisor supervisor,
            Factory factory) {
        mService = service;	// ActivityTaskManagerService
        mSupervisor = supervisor;	// ActivityStackSupervisor
        mHandler = new StartHandler(mService.mH.getLooper());	// DisplayThread
        mFactory = factory;		// 用来创建ActivityStarter对象给controller的工厂接口
        mFactory.setController(this);
        mPendingRemoteAnimationRegistry = new PendingRemoteAnimationRegistry(service,
                service.mH);	// 动画相关
    }

2.2 obtainStarter-获取ActivityStarter对象

ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }

3. ActivityStarter类

frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java

用来启动activity的

3.1 DefaultFactory-创建ActivityStarter对象的工厂接口

    static class DefaultFactory implements Factory {
        /**
         * The maximum count of starters that should be active at one time:
         * 1. last ran starter (for logging and post activity processing)
         * 2. current running starter
         * 3. starter from re-entry in (2)
         */
        private final int MAX_STARTER_COUNT = 3;

        private ActivityStartController mController;
        private ActivityTaskManagerService mService;
        private ActivityStackSupervisor mSupervisor;
        private ActivityStartInterceptor mInterceptor;

        private SynchronizedPool<ActivityStarter> mStarterPool =
                new SynchronizedPool<>(MAX_STARTER_COUNT);

        DefaultFactory(ActivityTaskManagerService service,
                ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
            mService = service;
            mSupervisor = supervisor;
            mInterceptor = interceptor;
        }

        @Override
        public void setController(ActivityStartController controller) {
            mController = controller;
        }

        @Override// 获取ActivityStarter对象
        public ActivityStarter obtain() {
            ActivityStarter starter = mStarterPool.acquire();

            if (starter == null) {
                starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
            }

            return starter;
        }

        @Override// 回收ActivityStarter对象
        public void recycle(ActivityStarter starter) {
            starter.reset(true /* clearRequest*/);
            mStarterPool.release(starter);
        }
    }

3.2 Request类-启动应用的信息保存-可以使用dump打印出来

设置的参数:mRequest.intent		Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] }mRequest.reason		startActivityAsUsermRequest.caller		launcher3的application threadmRequest.resolvedType	nullmRequest.resultTo		Token{e581a9b ActivityRecord{9a96eaa u0 com.android.launcher3/.Launcher t144}}mRequest.requestCode	-1mRequest.callingPackage		com.android.launcher3mRequest.resultWho		nullmRequest.startFlags		0mRequest.profilerInfo	nullmRequest.activityOptions	Bundle[mParcelledData.dataSize=276]mRequest.mayWait = true;mRequest.userId			0

3.3 execute-开始启动应用

    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(默认-1),
                        mRequest.callingPackage, mRequest.realCallingPid(默认0), mRequest.realCallingUid(默认-1),
                        mRequest.intent, mRequest.resolvedType,
                        mRequest.voiceSession(null), mRequest.voiceInteractor(null), mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig(null),
                        mRequest.activityOptions, mRequest.ignoreTargetSecurity(false), mRequest.userId,
                        mRequest.inTask(null), mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup(true),
                        mRequest.originatingPendingIntent(null), mRequest.allowBackgroundActivityStart(false));
            } 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,
                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
            }
        } finally {
            // controller做回收activitystater对象的工作
            onExecutionComplete();
        }
    }

3.4 startActivityMayWait-启动应用

    private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
        // Refuse possible leaked file descriptors
        // intent传文件描述符过来,文件描述符可能泄露了
        if (intent != null && intent.hasFileDescriptors()) {
            throw new IllegalArgumentException("File descriptors passed in Intent");
        }// tracker相关
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(intent);
        // 这个为true
        boolean componentSpecified = intent.getComponent() != null;
// 2343:launcher进程的pid号
        final int realCallingPid = requestRealCallingPid != Request.DEFAULT_REAL_CALLING_PID
                ? requestRealCallingPid	
                : Binder.getCallingPid();
        // 10081:launcher的uid号
        final int realCallingUid = requestRealCallingUid != Request.DEFAULT_REAL_CALLING_UID
                ? requestRealCallingUid	
                : Binder.getCallingUid();

        int callingPid;
        if (callingUid >= 0) {
            callingPid = -1;
        } else if (caller == null) {
            callingPid = realCallingPid;
            callingUid = realCallingUid;
        } else {
            callingPid = callingUid = -1;	// 走这里,-1
        }

        // Save a copy in case ephemeral needs it
        // 创建一个intent的副本
        final Intent ephemeralIntent = new Intent(intent);
        // Don't modify the client's object!
        // 又创建一个副本,用来修改的
        intent = new Intent(intent);
        if (componentSpecified
                && !(Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() == null)
                && !Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE.equals(intent.getAction())
                && !Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE.equals(intent.getAction())
                && mService.getPackageManagerInternalLocked()
                        .isInstantAppInstallerComponent(intent.getComponent())) {
            // intercept intents targeted directly to the ephemeral installer the
            // ephemeral installer should never be started with a raw Intent; instead
            // adjust the intent so it looks like a "normal" instant app launch
            // instant app相关的,应该就是快应用这种的
            intent.setComponent(null /*component*/);
            componentSpecified = false;
        }
// 1. 调用PMS来解析intent了,获取到了activityInfo和applicationInfo的信息
        ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                0 /* matchFlags */,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));
        
        if (rInfo == null) {// 不为null,不走进去
            UserInfo userInfo = mSupervisor.getUserInfo(userId);
            if (userInfo != null && userInfo.isManagedProfile()) {
                // Special case for managed profiles, if attempting to launch non-cryto aware
                // app in a locked managed profile from an unlocked parent allow it to resolve
                // as user will be sent via confirm credentials to unlock the profile.
                UserManager userManager = UserManager.get(mService.mContext);
                boolean profileLockedAndParentUnlockingOrUnlocked = false;
                long token = Binder.clearCallingIdentity();
                try {
                    UserInfo parent = userManager.getProfileParent(userId);
                    profileLockedAndParentUnlockingOrUnlocked = (parent != null)
                            && userManager.isUserUnlockingOrUnlocked(parent.id)
                            && !userManager.isUserUnlockingOrUnlocked(userId);
                } finally {
                    Binder.restoreCallingIdentity(token);
                }
                if (profileLockedAndParentUnlockingOrUnlocked) {
                    rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                            PackageManager.MATCH_DIRECT_BOOT_AWARE
                                    | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                            computeResolveFilterUid(
                                    callingUid, realCallingUid, mRequest.filterCallingUid));
                }
            }
        }
        // Collect information about the target of the Intent.
        // 2. 根据resolveInfo信息来获取activityInfo信息
        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

        synchronized (mService.mGlobalLock) {
            // 这里获取到了Launcher3的activityStack了
            final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
            stack.mConfigWillChange = globalConfig != null
                    && mService.getGlobalConfiguration().diff(globalConfig) != 0;
            if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                    "Starting activity when config will change = " + stack.mConfigWillChange);

            final long origId = Binder.clearCallingIdentity();

            if (aInfo != null &&// 不走这里
                    (aInfo.applicationInfo.privateFlags
                            & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0 &&
                    mService.mHasHeavyWeightFeature) {
                // This may be a heavy-weight process!  Check to see if we already
                // have another, different heavy-weight process running.
                if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
                    final WindowProcessController heavy = mService.mHeavyWeightProcess;
                    if (heavy != null && (heavy.mInfo.uid != aInfo.applicationInfo.uid
                            || !heavy.mName.equals(aInfo.processName))) {
                        int appCallingUid = callingUid;
                        if (caller != null) {
                            WindowProcessController callerApp =
                                    mService.getProcessController(caller);
                            if (callerApp != null) {
                                appCallingUid = callerApp.mInfo.uid;
                            } else {
                                Slog.w(TAG, "Unable to find app for caller " + caller
                                        + " (pid=" + callingPid + ") when starting: "
                                        + intent.toString());
                                SafeActivityOptions.abort(options);
                                return ActivityManager.START_PERMISSION_DENIED;
                            }
                        }

                        IIntentSender target = mService.getIntentSenderLocked(
                                ActivityManager.INTENT_SENDER_ACTIVITY, "android",
                                appCallingUid, userId, null, null, 0, new Intent[] { intent },
                                new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
                                        | PendingIntent.FLAG_ONE_SHOT, null);

                        Intent newIntent = new Intent();
                        if (requestCode >= 0) {
                            // Caller is requesting a result.
                            newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
                        }
                        newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
                                new IntentSender(target));
                        heavy.updateIntentForHeavyWeightActivity(newIntent);
                        newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
                                aInfo.packageName);
                        newIntent.setFlags(intent.getFlags());
                        newIntent.setClassName("android",
                                HeavyWeightSwitcherActivity.class.getName());
                        intent = newIntent;
                        resolvedType = null;
                        caller = null;
                        callingUid = Binder.getCallingUid();
                        callingPid = Binder.getCallingPid();
                        componentSpecified = true;
                        rInfo = mSupervisor.resolveIntent(intent, null /*resolvedType*/, userId,
                                0 /* matchFlags */, computeResolveFilterUid(
                                        callingUid, realCallingUid, mRequest.filterCallingUid));
                        aInfo = rInfo != null ? rInfo.activityInfo : null;
                        if (aInfo != null) {
                            aInfo = mService.mAmInternal.getActivityInfoForUser(aInfo, userId);
                        }
                    }
                }
            }
// 新建一个activityRecord
            final ActivityRecord[] outRecord = new ActivityRecord[1];
            // 3. 启动应用-585行
            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, originatingPendingIntent,
                    allowBackgroundActivityStart);

            Binder.restoreCallingIdentity(origId);

            if (stack.mConfigWillChange) {// 不走进去
                // If the caller also wants to switch to a new configuration,
                // do so now.  This allows a clean switch, as we are waiting
                // for the current activity to pause (so we will not destroy
                // it), and have not yet started the next activity.
                mService.mAmInternal.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
                        "updateConfiguration()");
                stack.mConfigWillChange = false;
                if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                        "Updating to new configuration after starting activity.");
                mService.updateConfigurationLocked(globalConfig, null, false);
            }

            // Notify ActivityMetricsLogger that the activity has launched. ActivityMetricsLogger
            // will then wait for the windows to be drawn and populate WaitResult.
            mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
            if (outResult != null) {// 不走进去
                outResult.result = res;

                final ActivityRecord r = outRecord[0];

                switch(res) {
                    case START_SUCCESS: {
                        mSupervisor.mWaitingActivityLaunched.add(outResult);
                        do {
                            try {
                                mService.mGlobalLock.wait();
                            } catch (InterruptedException e) {
                            }
                        } while (outResult.result != START_TASK_TO_FRONT
                                && !outResult.timeout && outResult.who == null);
                        if (outResult.result == START_TASK_TO_FRONT) {
                            res = START_TASK_TO_FRONT;
                        }
                        break;
                    }
                    case START_DELIVERED_TO_TOP: {
                        outResult.timeout = false;
                        outResult.who = r.mActivityComponent;
                        outResult.totalTime = 0;
                        break;
                    }
                    case START_TASK_TO_FRONT: {
                        outResult.launchState =
                                r.attachedToProcess() ? LAUNCH_STATE_HOT : LAUNCH_STATE_COLD;
                        // ActivityRecord may represent a different activity, but it should not be
                        // in the resumed state.
                        if (r.nowVisible && r.isState(RESUMED)) {
                            outResult.timeout = false;
                            outResult.who = r.mActivityComponent;
                            outResult.totalTime = 0;
                        } else {
                            final long startTimeMs = SystemClock.uptimeMillis();
                            mSupervisor.waitActivityVisible(
                                    r.mActivityComponent, outResult, startTimeMs);
                            // Note: the timeout variable is not currently not ever set.
                            do {
                                try {
                                    mService.mGlobalLock.wait();
                                } catch (InterruptedException e) {
                                }
                            } while (!outResult.timeout && outResult.who == null);
                        }
                        break;
                    }
                }
            }
// 这里直接返回了
            return res;
        }
    }

3.5 startActivity-启动应用-585行

    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,            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {        if (TextUtils.isEmpty(reason)) {            throw new IllegalArgumentException("Need to specify a reason.");        }        mLastStartReason = reason;        mLastStartActivityTimeMs = System.currentTimeMillis();        mLastStartActivityRecord[0] = null;// 1. 启动应用-622行        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, originatingPendingIntent,                allowBackgroundActivityStart);        if (outActivity != null) {            // mLastStartActivityRecord[0] is set in the call to startActivity above.            outActivity[0] = mLastStartActivityRecord[0];        }        return getExternalResult(mLastStartActivityResult);    }

3.6 startActivity-启动应用-622行

// caller:launcher的application thread;
// Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] } 
// Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 pkg=com.android.gallery3d cmp=com.android.gallery3d/.app.GalleryActivity bnds=[350,426][460,552] }
// resolvedType为null;ActivityInfo{4290c0 com.android.gallery3d.app.GalleryActivity};
// ResolveInfo{8f251f9 com.android.gallery3d/.app.GalleryActivity m=0x0};
// voiceSession为null;voiceInteractor为null;resultTo为Token{e3bd3d2 ActivityRecord{445fe5d u0 com.android.launcher3/.Launcher t9}}
// resultWho为null;requestCode为-1;callingPid为-1;callingUid为-1;callingPackage为com.android.launcher3
// realCallingPid为4739;realCallingUid为10081(都为launcher);startFlags为0;options有classloader
// ignoreTargetSecurity为false;componentSpecified为true;outActivity的元素为null
// inTask为null;allowPendingRemoteAnimationRegistryLookup为true;originatingPendingIntent为null;allowBackgroundActivityStart为false
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,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
    // 开头,trace相关,侦听activity启动
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(intent);
        int err = ActivityManager.START_SUCCESS;
        // Pull the optional Ephemeral Installer-only bundle out of the options early.
        final Bundle verificationBundle
                = options != null ? options.popAppVerificationBundle() : null;

        WindowProcessController callerApp = null;
        if (caller != null) {
            callerApp = mService.getProcessController(caller);
            if (callerApp != null) {
                callingPid = callerApp.getPid();// launcher3的pid
                callingUid = callerApp.mInfo.uid;// launcher3的uid
            } else {
                Slog.w(TAG, "Unable to find app for caller " + caller
                        + " (pid=" + callingPid + ") when starting: "
                        + intent.toString());
                err = ActivityManager.START_PERMISSION_DENIED;
            }
        }

        final int userId = aInfo != null && aInfo.applicationInfo != null
                ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;

        if (err == ActivityManager.START_SUCCESS) {
            // 打印START u
            Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
                    + "} from uid " + callingUid);
        }

        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null;
    // resultTo为launcher3
        if (resultTo != null) {
            // sourceRecord也为launcher3
            sourceRecord = mRootActivityContainer.isInAnyStack(resultTo);
            if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                    "Will send result to " + resultTo + " " + sourceRecord);
            if (sourceRecord != null) {
                if (requestCode >= 0 && !sourceRecord.finishing) {
                    resultRecord = sourceRecord;
                }
            }
        }
// launcheflags为270532608
        final int launchFlags = intent.getFlags();
// 没有这个flags,不走下面
        if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
            // Transfer the result target from the source activity to the new
            // one being started, including any failures.
            if (requestCode >= 0) {
                SafeActivityOptions.abort(options);
                return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
            }
            resultRecord = sourceRecord.resultTo;
            if (resultRecord != null && !resultRecord.isInStackLocked()) {
                resultRecord = null;
            }
            resultWho = sourceRecord.resultWho;
            requestCode = sourceRecord.requestCode;
            sourceRecord.resultTo = null;
            if (resultRecord != null) {
                resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
            }
            if (sourceRecord.launchedFromUid == callingUid) {
                // The new activity is being launched from the same uid as the previous
                // activity in the flow, and asking to forward its result back to the
                // previous.  In this case the activity is serving as a trampoline between
                // the two, so we also want to update its launchedFromPackage to be the
                // same as the previous activity.  Note that this is safe, since we know
                // these two packages come from the same uid; the caller could just as
                // well have supplied that same package name itself.  This specifially
                // deals with the case of an intent picker/chooser being launched in the app
                // flow to redirect to an activity picked by the user, where we want the final
                // activity to consider it to have been launched by the previous app activity.
                callingPackage = sourceRecord.launchedFromPackage;
            }
        }
// intent.getComponent()为null
        if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
            // We couldn't find a class that can handle the given Intent.
            // That's the end of that!
            err = ActivityManager.START_INTENT_NOT_RESOLVED;
        }
// aInfo不为null
        if (err == ActivityManager.START_SUCCESS && aInfo == null) {
            // We couldn't find the specific class specified in the Intent.
            // Also the end of the line.
            err = ActivityManager.START_CLASS_NOT_FOUND;
        }
// voiceSession为null
        if (err == ActivityManager.START_SUCCESS && sourceRecord != null
                && sourceRecord.getTaskRecord().voiceSession != null) {
            // If this activity is being launched as part of a voice session, we need
            // to ensure that it is safe to do so.  If the upcoming activity will also
            // be part of the voice session, we can only launch it if it has explicitly
            // said it supports the VOICE category, or it is a part of the calling app.
            if ((launchFlags & FLAG_ACTIVITY_NEW_TASK) == 0
                    && sourceRecord.info.applicationInfo.uid != aInfo.applicationInfo.uid) {
                try {
                    intent.addCategory(Intent.CATEGORY_VOICE);
                    if (!mService.getPackageManager().activitySupportsIntent(
                            intent.getComponent(), intent, resolvedType)) {
                        Slog.w(TAG,
                                "Activity being started in current voice task does not support voice: "
                                        + intent);
                        err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
                    }
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failure checking voice capabilities", e);
                    err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
                }
            }
        }
// voiceSession为null
        if (err == ActivityManager.START_SUCCESS && voiceSession != null) {
            // If the caller is starting a new voice session, just make sure the target
            // is actually allowing it to run this way.
            try {
                if (!mService.getPackageManager().activitySupportsIntent(intent.getComponent(),
                        intent, resolvedType)) {
                    Slog.w(TAG,
                            "Activity being started in new voice task does not support: "
                                    + intent);
                    err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
                }
            } catch (RemoteException e) {
                Slog.w(TAG, "Failure checking voice capabilities", e);
                err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
            }
        }
// resultStack = resultRecord为null
        final ActivityStack resultStack = resultRecord == null
                ? null : resultRecord.getActivityStack();
// err为START_SUCCESS
        if (err != START_SUCCESS) {
            if (resultRecord != null) {
                resultStack.sendActivityResultLocked(
                        -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
            }
            SafeActivityOptions.abort(options);
            return err;
        }
// 检查callerApp(launcher3)是否有权限启动activity
        boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
                requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
                inTask != null, callerApp, resultRecord, resultStack);
        abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
                callingPid, resolvedType, aInfo.applicationInfo);
        abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
                callingPackage);

        boolean restrictedBgActivity = false;
        if (!abort) {// abort为false,走这里
            try {
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
                        "shouldAbortBackgroundActivityStart");
                // restrictedBgActivity为false
                restrictedBgActivity = shouldAbortBackgroundActivityStart(callingUid,
                        callingPid, callingPackage, realCallingUid, realCallingPid, callerApp,
                        originatingPendingIntent, allowBackgroundActivityStart, intent);
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }

        // Merge the two options bundles, while realCallerOptions takes precedence.
    // ActivityOptions(36191336), mPackageName=null, mAnimationType=13, mStartX=0, mStartY=0, mWidth=0, mHeight=0
        ActivityOptions checkedOptions = options != null
                ? options.getOptions(intent, aInfo, callerApp, mSupervisor) : null;
        if (allowPendingRemoteAnimationRegistryLookup) {
            checkedOptions = mService.getActivityStartController()
                    .getPendingRemoteAnimationRegistry()
                    .overrideOptionsIfNeeded(callingPackage, checkedOptions);
        }
        if (mService.mController != null) {// 为null,不走下面
            try {
                // The Intent we give to the watcher has the extra data
                // stripped off, since it can contain private information.
                Intent watchIntent = intent.cloneFilter();
                abort |= !mService.mController.activityStarting(watchIntent,
                        aInfo.applicationInfo.packageName);
            } catch (RemoteException e) {
                mService.mController = null;
            }
        }
// 只是赋值
        mInterceptor.setStates(userId, realCallingPid, realCallingUid, startFlags, callingPackage);
    // 看是否拦截activity
        if (mInterceptor.intercept(intent, rInfo, aInfo, resolvedType, inTask, callingPid,
                callingUid, checkedOptions)) {
            // 活动开始被拦截,例如 因为目标用户当前处于安静模式(关闭工作)或目标应用程序被挂起
            // activity start was intercepted, e.g. because the target user is currently in quiet
            // mode (turn off work) or the target application is suspended
            intent = mInterceptor.mIntent;
            rInfo = mInterceptor.mRInfo;
            aInfo = mInterceptor.mAInfo;
            resolvedType = mInterceptor.mResolvedType;
            inTask = mInterceptor.mInTask;
            callingPid = mInterceptor.mCallingPid;
            callingUid = mInterceptor.mCallingUid;
            checkedOptions = mInterceptor.mActivityOptions;
        }

        if (abort) {// false,不走下面
            if (resultRecord != null) {
                resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
                        RESULT_CANCELED, null);
            }
            // We pretend to the caller that it was really started, but
            // they will just get a cancel result.
            ActivityOptions.abort(checkedOptions);
            return START_ABORTED;
        }

        // If permissions need a review before any of the app components can run, we
        // launch the review activity and pass a pending intent to start the activity
        // we are to launching now after the review is completed.
        if (aInfo != null) {
            // 如果在任何应用程序组件可以运行之前权限需要审查,我们会启动审查活动并传递一个挂起的意图,以在审查完成后启动我们现在要启动的活动。
            // 检查权限,为false,不走进去
            if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
                    aInfo.packageName, userId)) {
                IIntentSender target = mService.getIntentSenderLocked(
                        ActivityManager.INTENT_SENDER_ACTIVITY, callingPackage,
                        callingUid, userId, null, null, 0, new Intent[]{intent},
                        new String[]{resolvedType}, PendingIntent.FLAG_CANCEL_CURRENT
                                | PendingIntent.FLAG_ONE_SHOT, null);

                Intent newIntent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);

                int flags = intent.getFlags();
                flags |= Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;

                /*
                 * Prevent reuse of review activity: Each app needs their own review activity. By
                 * default activities launched with NEW_TASK or NEW_DOCUMENT try to reuse activities
                 * with the same launch parameters (extras are ignored). Hence to avoid possible
                 * reuse force a new activity via the MULTIPLE_TASK flag.
                 *
                 * Activities that are not launched with NEW_TASK or NEW_DOCUMENT are not re-used,
                 * hence no need to add the flag in this case.
                 */
                if ((flags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_NEW_DOCUMENT)) != 0) {
                    flags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
                }
                newIntent.setFlags(flags);

                newIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, aInfo.packageName);
                newIntent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
                if (resultRecord != null) {
                    newIntent.putExtra(Intent.EXTRA_RESULT_NEEDED, true);
                }
                intent = newIntent;

                resolvedType = null;
                callingUid = realCallingUid;
                callingPid = realCallingPid;

                rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));
                aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                        null /*profilerInfo*/);

                if (DEBUG_PERMISSIONS_REVIEW) {
                    final ActivityStack focusedStack =
                            mRootActivityContainer.getTopDisplayFocusedStack();
                    Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true,
                            true, false) + "} from uid " + callingUid + " on display "
                            + (focusedStack == null ? DEFAULT_DISPLAY : focusedStack.mDisplayId));
                }
            }
        }

        // If we have an ephemeral app, abort the process of launching the resolved intent.
        // Instead, launch the ephemeral installer. Once the installer is finished, it
        // starts either the intent we resolved here [on install error] or the ephemeral
        // app [on install success].
    // 如果我们有一个临时应用程序,请中止启动已解析意图的过程。 相反,启动临时安装程序。 安装程序完成后,它会启动我们在此处解决的意图 [on app [on install success]。
    // 临时安装程序,不走进去
        if (rInfo != null && rInfo.auxiliaryInfo != null) {
            intent = createLaunchIntent(rInfo.auxiliaryInfo, ephemeralIntent,
                    callingPackage, verificationBundle, resolvedType, userId);
            resolvedType = null;
            callingUid = realCallingUid;
            callingPid = realCallingPid;

            aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/);
        }
// 创建ActivityRecord
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                mSupervisor, checkedOptions, sourceRecord);
        if (outActivity != null) {
            // 放到outActivity中
            outActivity[0] = r;
        }

        if (r.appTimeTracker == null && sourceRecord != null) {
            // If the caller didn't specify an explicit time tracker, we want to continue
            // tracking under any it has.
            // 如果调用者没有指定明确的时间跟踪器,我们希望继续跟踪它所拥有的任何时间。
            r.appTimeTracker = sourceRecord.appTimeTracker;
        }

        final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();

        // If we are starting an activity that is not from the same uid as the currently resumed
        // one, check whether app switches are allowed.
    // 如果我们启动的 Activity 与当前恢复的 uid 不同,请检查是否允许应用切换。
    // 不走进去
        if (voiceSession == null && (stack.getResumedActivity() == null
                || stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) {
            if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
                    realCallingPid, realCallingUid, "Activity start")) {
                if (!(restrictedBgActivity && handleBackgroundActivityAbort(r))) {
                    mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
                            sourceRecord, startFlags, stack, callerApp));
                }
                ActivityOptions.abort(checkedOptions);
                return ActivityManager.START_SWITCHES_CANCELED;
            }
        }
// 这是自我们停止切换以来的第二个允许切换,所以现在一般只允许切换。 用例: - 用户按下 home(禁用开关,切换到 home,mDidAppSwitch 现在为 true); - 用户点击一个主页图标(来自家所以允许,我们点击这里,现在允许任何人再次切换)。
        mService.onStartActivitySetDidAppSwitch();
    // 没有pendingactivity,啥都没做
        mController.doPendingActivityLaunches(false);
// 启动activity-1396行
        final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
    // 结尾,trace相关
        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
        return res;
    }

3.7 shouldAbortBackgroundActivityStart-返回false,没有abort

    boolean shouldAbortBackgroundActivityStart(int callingUid, int callingPid,            final String callingPackage, int realCallingUid, int realCallingPid,            WindowProcessController callerApp, PendingIntentRecord originatingPendingIntent,            boolean allowBackgroundActivityStart, Intent intent) {        // don't abort for the most important UIDs        final int callingAppId = UserHandle.getAppId(callingUid);        // 不能中断root system nfc这些        if (callingUid == Process.ROOT_UID || callingAppId == Process.SYSTEM_UID                || callingAppId == Process.NFC_UID) {            return false;        }        // don't abort if the callingUid has a visible window or is a persistent system process        final int callingUidProcState = mService.getUidState(callingUid);// 2        final boolean callingUidHasAnyVisibleWindow =// true                mService.mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(callingUid);        final boolean isCallingUidForeground = callingUidHasAnyVisibleWindow// true                || callingUidProcState == ActivityManager.PROCESS_STATE_TOP                || callingUidProcState == ActivityManager.PROCESS_STATE_BOUND_TOP;        final boolean isCallingUidPersistentSystemProcess =// false                callingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;        if (callingUidHasAnyVisibleWindow(true) || isCallingUidPersistentSystemProcess) {            return false;// 这里返回false        }        // take realCallingUid into consideration        final int realCallingUidProcState = (callingUid == realCallingUid)                ? callingUidProcState                : mService.getUidState(realCallingUid);        final boolean realCallingUidHasAnyVisibleWindow = (callingUid == realCallingUid)                ? callingUidHasAnyVisibleWindow                : mService.mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(realCallingUid);        final boolean isRealCallingUidForeground = (callingUid == realCallingUid)                ? isCallingUidForeground                : realCallingUidHasAnyVisibleWindow                        || realCallingUidProcState == ActivityManager.PROCESS_STATE_TOP;        final int realCallingAppId = UserHandle.getAppId(realCallingUid);        final boolean isRealCallingUidPersistentSystemProcess = (callingUid == realCallingUid)                ? isCallingUidPersistentSystemProcess                : (realCallingAppId == Process.SYSTEM_UID)                        || realCallingUidProcState <= ActivityManager.PROCESS_STATE_PERSISTENT_UI;        if (realCallingUid != callingUid) {            // don't abort if the realCallingUid has a visible window            if (realCallingUidHasAnyVisibleWindow) {                return false;            }            // if the realCallingUid is a persistent system process, abort if the IntentSender            // wasn't whitelisted to start an activity            if (isRealCallingUidPersistentSystemProcess && allowBackgroundActivityStart) {                return false;            }            // don't abort if the realCallingUid is an associated companion app            if (mService.isAssociatedCompanionApp(UserHandle.getUserId(realCallingUid),                    realCallingUid)) {                return false;            }        }        // don't abort if the callingUid has START_ACTIVITIES_FROM_BACKGROUND permission        if (mService.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)                == PERMISSION_GRANTED) {            return false;        }        // don't abort if the caller has the same uid as the recents component        if (mSupervisor.mRecentTasks.isCallerRecents(callingUid)) {            return false;        }        // don't abort if the callingUid is the device owner        if (mService.isDeviceOwner(callingUid)) {            return false;        }        // don't abort if the callingUid has companion device        final int callingUserId = UserHandle.getUserId(callingUid);        if (mService.isAssociatedCompanionApp(callingUserId, callingUid)) {            return false;        }        // If we don't have callerApp at this point, no caller was provided to startActivity().        // That's the case for PendingIntent-based starts, since the creator's process might not be        // up and alive. If that's the case, we retrieve the WindowProcessController for the send()        // caller, so that we can make the decision based on its foreground/whitelisted state.        int callerAppUid = callingUid;        if (callerApp == null) {            callerApp = mService.getProcessController(realCallingPid, realCallingUid);            callerAppUid = realCallingUid;        }        // don't abort if the callerApp or other processes of that uid are whitelisted in any way        if (callerApp != null) {            // first check the original calling process            if (callerApp.areBackgroundActivityStartsAllowed()) {                return false;            }            // only if that one wasn't whitelisted, check the other ones            final ArraySet<WindowProcessController> uidProcesses =                    mService.mProcessMap.getProcesses(callerAppUid);            if (uidProcesses != null) {                for (int i = uidProcesses.size() - 1; i >= 0; i--) {                    final WindowProcessController proc = uidProcesses.valueAt(i);                    if (proc != callerApp && proc.areBackgroundActivityStartsAllowed()) {                        return false;                    }                }            }        }        // don't abort if the callingUid has SYSTEM_ALERT_WINDOW permission        if (mService.hasSystemAlertWindowPermission(callingUid, callingPid, callingPackage)) {            Slog.w(TAG, "Background activity start for " + callingPackage                    + " allowed because SYSTEM_ALERT_WINDOW permission is granted.");            return false;        }        // anything that has fallen through would currently be aborted        Slog.w(TAG, "Background activity start [callingPackage: " + callingPackage                + "; callingUid: " + callingUid                + "; isCallingUidForeground: " + isCallingUidForeground                + "; isCallingUidPersistentSystemProcess: " + isCallingUidPersistentSystemProcess                + "; realCallingUid: " + realCallingUid                + "; isRealCallingUidForeground: " + isRealCallingUidForeground                + "; isRealCallingUidPersistentSystemProcess: "                + isRealCallingUidPersistentSystemProcess                + "; originatingPendingIntent: " + originatingPendingIntent                + "; isBgStartWhitelisted: " + allowBackgroundActivityStart                + "; intent: " + intent                + "; callerApp: " + callerApp                + "]");        // log aborted activity start to TRON        if (mService.isActivityStartsLoggingEnabled()) {            mSupervisor.getActivityMetricsLogger().logAbortedBgActivityStart(intent, callerApp,                    callingUid, callingPackage, callingUidProcState, callingUidHasAnyVisibleWindow,                    realCallingUid, realCallingUidProcState, realCallingUidHasAnyVisibleWindow,                    (originatingPendingIntent != null));        }        return true;    }

3.8 startActivity-启动activity-1396行

    private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        int result = START_CANCELED;
        final ActivityStack startedActivityStack;
        try {
            // 推迟布局传递
            mService.mWindowManager.deferSurfaceLayout();
            // 启动activity
            result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
        } finally {
            // startactivity返回结果处理
            final ActivityStack currentStack = r.getActivityStack();
            startedActivityStack = currentStack != null ? currentStack : mTargetStack;

            if (ActivityManager.isStartResultSuccessful(result)) {
                if (startedActivityStack != null) {// 走这里
                    // If there is no state change (e.g. a resumed activity is reparented to
                    // top of another display) to trigger a visibility/configuration checking,
                    // we have to update the configuration for changing to different display.
                    final ActivityRecord currentTop =
                            startedActivityStack.topRunningActivityLocked();
                    if (currentTop != null && currentTop.shouldUpdateConfigForDisplayChanged()) {// 没有走进去
                        mRootActivityContainer.ensureVisibilityAndConfig(
                                currentTop, currentTop.getDisplayId(),
                                true /* markFrozenIfConfigChanged */, false /* deferResume */);
                    }
                }
            } else {
                // If we are not able to proceed, disassociate the activity from the task.
                // Leaving an activity in an incomplete state can lead to issues, such as
                // performing operations without a window container.
                final ActivityStack stack = mStartActivity.getActivityStack();
                if (stack != null) {
                    stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                            null /* intentResultData */, "startActivity", true /* oomAdj */);
                }

                // Stack should also be detached from display and be removed if it's empty.
                if (startedActivityStack != null && startedActivityStack.isAttached()
                        && startedActivityStack.numActivities() == 0
                        && !startedActivityStack.isActivityTypeHome()) {
                    startedActivityStack.remove();
                }
            }
            mService.mWindowManager.continueSurfaceLayout();
        }
// 这里是干嘛的?
        postStartActivityProcessing(r, result, startedActivityStack);

        return result;
    }

3.9 startActivityUnchecked-启动activity-1473行

    // Note: This method should only be called from {@link startActivity}.
// private函数,只能被startActivity函数调用
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        // 1. 根据传进来的flags,进行初始化操作
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor, restrictedBgActivity);

        final int preferredWindowingMode = mLaunchParams.mWindowingMode;// 0
// 啥都没做
        computeLaunchingTaskFlags();
// 获取mSourceStack:mSourceStack = mSourceRecord.getActivityStack();
        computeSourceStack();

        mIntent.setFlags(mLaunchFlags);
// 决定是否应将新活动插入到现有任务中。 如果不是,则返回 null 或带有应添加新活动的任务的 ActivityRecord。
        ActivityRecord reusedActivity = getReusableIntentActivity();// null
// 计算LaunchParams的值
        mSupervisor.getLaunchParamsController().calculate(
                reusedActivity != null ? reusedActivity.getTaskRecord() : mInTask,
                r.info.windowLayout, r, sourceRecord, options, PHASE_BOUNDS, mLaunchParams);
        mPreferredDisplayId =
                mLaunchParams.hasPreferredDisplay() ? mLaunchParams.mPreferredDisplayId
                        : DEFAULT_DISPLAY;// 0

        // If requested, freeze the task list
        if (mOptions != null && mOptions.freezeRecentTasksReordering()
                && mSupervisor.mRecentTasks.isCallerRecents(r.launchedFromUid)
                && !mSupervisor.mRecentTasks.isFreezeTaskListReorderingSet()) {// 为false,不走进去
            mFrozeTaskList = true;
            mSupervisor.mRecentTasks.setFreezeTaskListReordering();
        }

        // Do not start home activity if it cannot be launched on preferred display. We are not
        // doing this in ActivityStackSupervisor#canPlaceEntityOnDisplay because it might
        // fallback to launch on other displays.
        if (r.isActivityTypeHome() && !mRootActivityContainer.canStartHomeOnDisplay(r.info,
                mPreferredDisplayId, true /* allowInstrumenting */)) {// 为false,不走进去
            Slog.w(TAG, "Cannot launch home on display " + mPreferredDisplayId);
            return START_CANCELED;
        }

        if (reusedActivity != null) {// 为false,不走进去
            // When the flags NEW_TASK and CLEAR_TASK are set, then the task gets reused but
            // still needs to be a lock task mode violation since the task gets cleared out and
            // the device would otherwise leave the locked task.
            if (mService.getLockTaskController().isLockTaskModeViolation(
                    reusedActivity.getTaskRecord(),
                    (mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
                            == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {
                Slog.e(TAG, "startActivityUnchecked: Attempt to violate Lock Task Mode");
                return START_RETURN_LOCK_TASK_MODE_VIOLATION;
            }

            // True if we are clearing top and resetting of a standard (default) launch mode
            // ({@code LAUNCH_MULTIPLE}) activity. The existing activity will be finished.
            final boolean clearTopAndResetStandardLaunchMode =
                    (mLaunchFlags & (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED))
                            == (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                    && mLaunchMode == LAUNCH_MULTIPLE;

            // If mStartActivity does not have a task associated with it, associate it with the
            // reused activity's task. Do not do so if we're clearing top and resetting for a
            // standard launchMode activity.
            if (mStartActivity.getTaskRecord() == null && !clearTopAndResetStandardLaunchMode) {
                mStartActivity.setTask(reusedActivity.getTaskRecord());
            }

            if (reusedActivity.getTaskRecord().intent == null) {
                // This task was started because of movement of the activity based on affinity...
                // Now that we are actually launching it, we can assign the base intent.
                reusedActivity.getTaskRecord().setIntent(mStartActivity);
            } else {
                final boolean taskOnHome =
                        (mStartActivity.intent.getFlags() & FLAG_ACTIVITY_TASK_ON_HOME) != 0;
                if (taskOnHome) {
                    reusedActivity.getTaskRecord().intent.addFlags(FLAG_ACTIVITY_TASK_ON_HOME);
                } else {
                    reusedActivity.getTaskRecord().intent.removeFlags(FLAG_ACTIVITY_TASK_ON_HOME);
                }
            }

            // This code path leads to delivering a new intent, we want to make sure we schedule it
            // as the first operation, in case the activity will be resumed as a result of later
            // operations.
            if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                    || isDocumentLaunchesIntoExisting(mLaunchFlags)
                    || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
                final TaskRecord task = reusedActivity.getTaskRecord();

                // In this situation we want to remove all activities from the task up to the one
                // being started. In most cases this means we are resetting the task to its initial
                // state.
                final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
                        mLaunchFlags);

                // The above code can remove {@code reusedActivity} from the task, leading to the
                // the {@code ActivityRecord} removing its reference to the {@code TaskRecord}. The
                // task reference is needed in the call below to
                // {@link setTargetStackAndMoveToFrontIfNeeded}.
                if (reusedActivity.getTaskRecord() == null) {
                    reusedActivity.setTask(task);
                }

                if (top != null) {
                    if (top.frontOfTask) {
                        // Activity aliases may mean we use different intents for the top activity,
                        // so make sure the task now has the identity of the new intent.
                        top.getTaskRecord().setIntent(mStartActivity);
                    }
                    deliverNewIntent(top);
                }
            }

            mRootActivityContainer.sendPowerHintForLaunchStartIfNeeded
                    (false /* forceSend */, reusedActivity);

            reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);

            final ActivityRecord outResult =
                    outActivity != null && outActivity.length > 0 ? outActivity[0] : null;

            // When there is a reused activity and the current result is a trampoline activity,
            // set the reused activity as the result.
            if (outResult != null && (outResult.finishing || outResult.noDisplay)) {
                outActivity[0] = reusedActivity;
            }

            if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
                // We don't need to start a new activity, and the client said not to do anything
                // if that is the case, so this is it!  And for paranoia, make sure we have
                // correctly resumed the top activity.
                resumeTargetStackIfNeeded();
                return START_RETURN_INTENT_TO_CALLER;
            }

            if (reusedActivity != null) {
                setTaskFromIntentActivity(reusedActivity);

                if (!mAddingToTask && mReuseTask == null) {
                    // We didn't do anything...  but it was needed (a.k.a., client don't use that
                    // intent!)  And for paranoia, make sure we have correctly resumed the top activity.
                    resumeTargetStackIfNeeded();
                    if (outActivity != null && outActivity.length > 0) {
                        // The reusedActivity could be finishing, for example of starting an
                        // activity with FLAG_ACTIVITY_CLEAR_TOP flag. In that case, return the
                        // top running activity in the task instead.
                        outActivity[0] = reusedActivity.finishing
                                ? reusedActivity.getTaskRecord().getTopActivity() : reusedActivity;
                    }

                    return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;
                }
            }
        }

        if (mStartActivity.packageName == null) {// 为false,不走进去
            final ActivityStack sourceStack = mStartActivity.resultTo != null
                    ? mStartActivity.resultTo.getActivityStack() : null;
            if (sourceStack != null) {
                sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,
                        mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,
                        null /* data */);
            }
            ActivityOptions.abort(mOptions);
            return START_CLASS_NOT_FOUND;
        }

        // If the activity being launched is the same as the one currently at the top, then
        // we need to check if it should only be launched once.
        // 如果正在启动的活动与当前位于顶部的活动相同,那么我们需要检查它是否应该只启动一次。
        final ActivityStack topStack = mRootActivityContainer.getTopDisplayFocusedStack();
        final ActivityRecord topFocused = topStack.getTopActivity();
        final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
        final boolean dontStart = top != null && mStartActivity.resultTo == null
                && top.mActivityComponent.equals(mStartActivity.mActivityComponent)
                && top.mUserId == mStartActivity.mUserId
                && top.attachedToProcess()
                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK))
                // This allows home activity to automatically launch on secondary display when
                // display added, if home was the top activity on default display, instead of
                // sending new intent to the home activity on default display.
                && (!top.isActivityTypeHome() || top.getDisplayId() == mPreferredDisplayId);
        if (dontStart) {// 为false,不走进去
            // For paranoia, make sure we have correctly resumed the top activity.
            topStack.mLastPausedActivity = null;
            if (mDoResume) {
                mRootActivityContainer.resumeFocusedStacksTopActivities();
            }
            ActivityOptions.abort(mOptions);
            if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
                // We don't need to start a new activity, and the client said not to do
                // anything if that is the case, so this is it!
                return START_RETURN_INTENT_TO_CALLER;
            }

            deliverNewIntent(top);

            // Don't use mStartActivity.task to show the toast. We're not starting a new activity
            // but reusing 'top'. Fields in mStartActivity may not be fully initialized.
            mSupervisor.handleNonResizableTaskIfNeeded(top.getTaskRecord(), preferredWindowingMode,
                    mPreferredDisplayId, topStack);

            return START_DELIVERED_TO_TOP;
        }

        boolean newTask = false;
        final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                ? mSourceRecord.getTaskRecord() : null;// null

        // Should this be considered a new task?
        int result = START_SUCCESS;
        if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
            newTask = true;// 走这里
            // 1. 创建新的taskrecord并将activitystack移动到最前面
            result = setTaskFromReuseOrCreateNewTask(taskToAffiliate);
        } else if (mSourceRecord != null) {
            result = setTaskFromSourceRecord();
        } else if (mInTask != null) {
            result = setTaskFromInTask();
        } else {
            // This not being started from an existing activity, and not part of a new task...
            // just put it in the top task, though these days this case should never happen.
            result = setTaskToCurrentTopOrCreateNewTask();
        }
        if (result != START_SUCCESS) {
            return result;
        }
// 权限相关
        mService.mUgmInternal.grantUriPermissionFromIntent(mCallingUid, mStartActivity.packageName,
                mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.mUserId);
        mService.getPackageManagerInternalLocked().grantEphemeralAccess(
                mStartActivity.mUserId, mIntent, UserHandle.getAppId(mStartActivity.appInfo.uid),
                UserHandle.getAppId(mCallingUid));
        if (newTask) {// 为true,记录event log
            EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.mUserId,
                    mStartActivity.getTaskRecord().taskId);
        }// 记录event log
        ActivityStack.logStartActivity(
                EventLogTags.AM_CREATE_ACTIVITY, mStartActivity, mStartActivity.getTaskRecord());
        mTargetStack.mLastPausedActivity = null;

        mRootActivityContainer.sendPowerHintForLaunchStartIfNeeded(
                false /* forceSend */, mStartActivity);
// 2. 启动activity-做启动动画和启动窗口的工作
        mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
                mOptions);
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTaskRecord().topRunningActivityLocked();
            if (!mTargetStack.isFocusable()
                    || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                    && mStartActivity != topTaskActivity)) {
                // If the activity is not focusable, we can't resume it, but still would like to
                // make sure it becomes visible as it starts (this will also trigger entry
                // animation). An example of this are PIP activities.
                // Also, we don't want to resume activities in a task that currently has an overlay
                // as the starting activity just needs to be in the visible paused state until the
                // over is removed.
                mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
                // Go ahead and tell window manager to execute app transition for this activity
                // since the app transition will not be triggered through the resume channel.
                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.isFocusable()
                        && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {// 为false,不走这里
                    mTargetStack.moveToFront("startActivityUnchecked");
                }// 3. 启动activity,显示activity-重要
                mRootActivityContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        } else if (mStartActivity != null) {
            mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
        }// 什么都没做,就返回了
        mRootActivityContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
// split screen相关的,什么都没做就返回了
        mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTaskRecord(),
                preferredWindowingMode, mPreferredDisplayId, mTargetStack);

        return START_SUCCESS;
    }

3.10 setInitialState-设置初始化状态

    private void setInitialState(ActivityRecord r, ActivityOptions options, TaskRecord inTask,
            boolean doResume, int startFlags, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            boolean restrictedBgActivity) {
        // 重置 {@link ActivityStarter} 状态。 @param clearRequest 是否应将请求重置为默认值。
        // false说明不重置mRequest的值,这个就是execute的时候进行的赋值的mRequest
        reset(false /* clearRequest */);

        mStartActivity = r;
        mIntent = r.intent;
        mOptions = options;
        mCallingUid = r.launchedFromUid;
        mSourceRecord = sourceRecord;
        mVoiceSession = voiceSession;
        mVoiceInteractor = voiceInteractor;
        mRestrictedBgActivity = restrictedBgActivity;

        mLaunchParams.reset();

        // Preferred display id is the only state we need for now and it could be updated again
        // after we located a reusable task (which might be resided in another display).
        // 首选显示 id 是我们现在唯一需要的状态,在我们找到可重用的任务(可能驻留在另一个显示中)后,它可以再次更新。
        // 找preferreddisplayid
        mSupervisor.getLaunchParamsController().calculate(inTask, r.info.windowLayout, r,
                sourceRecord, options, PHASE_DISPLAY, mLaunchParams);
        mPreferredDisplayId =
                mLaunchParams.hasPreferredDisplay() ? mLaunchParams.mPreferredDisplayId
                        : DEFAULT_DISPLAY;

        mLaunchMode = r.launchMode;

        mLaunchFlags = adjustLaunchFlagsToDocumentMode(
                r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
                LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
        mLaunchTaskBehind = r.mLaunchTaskBehind
                && !isLaunchModeOneOf(LAUNCH_SINGLE_TASK, LAUNCH_SINGLE_INSTANCE)
                && (mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0;
// 看mStartActivity.resultTo != null && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0
        // 是否在新的task中运行这个activity,因为resultTo为null,所以什么都没做
        sendNewTaskResultRequestIfNeeded();

        if ((mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {// 为false,不走进去
            mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        }

        // If we are actually going to launch in to a new task, there are some cases where
        // we further want to do multiple task.
        // 如果我们真的要开始执行一项新任务,在某些情况下,我们会进一步执行多项任务。
        if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {// 为true
            if (mLaunchTaskBehind
                    || r.info.documentLaunchMode == DOCUMENT_LAUNCH_ALWAYS) {// 为false,不走进去
                mLaunchFlags |= FLAG_ACTIVITY_MULTIPLE_TASK;
            }
        }

        // We'll invoke onUserLeaving before onPause only if the launching
        // activity did not explicitly state that this is an automated launch.
        // 仅当启动活动未明确声明这是自动启动时,我们才会在 onPause 之前调用 onUserLeaving。
        mSupervisor.mUserLeaving = (mLaunchFlags & FLAG_ACTIVITY_NO_USER_ACTION) == 0;// 为true
        if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
                "startActivity() => mUserLeaving=" + mSupervisor.mUserLeaving);

        // If the caller has asked not to resume at this point, we make note
        // of this in the record so that we can skip it when trying to find
        // the top running activity.
        // 如果调用者此时要求不要继续,我们会在记录中记录这一点,以便我们在尝试查找运行最高的活动时可以跳过它。
        mDoResume = doResume;
        if (!doResume || !r.okToShowLocked()) {// doResume为true,不走进去
            r.delayedResume = true;
            mDoResume = false;
        }

        if (mOptions != null) {// 为true
            if (mOptions.getLaunchTaskId() != -1 && mOptions.getTaskOverlay()) {// 为false,不走进去
                r.mTaskOverlay = true;
                if (!mOptions.canTaskOverlayResume()) {
                    final TaskRecord task = mRootActivityContainer.anyTaskForId(
                            mOptions.getLaunchTaskId());
                    final ActivityRecord top = task != null ? task.getTopActivity() : null;
                    if (top != null && !top.isState(RESUMED)) {

                        // The caller specifies that we'd like to be avoided to be moved to the
                        // front, so be it!
                        mDoResume = false;
                        mAvoidMoveToFront = true;
                    }
                }
            } else if (mOptions.getAvoidMoveToFront()) {// 为false,不走进去
                mDoResume = false;
                mAvoidMoveToFront = true;
            }
        }

        mNotTop = (mLaunchFlags & FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? sourceRecord : null;// null

        mInTask = inTask;// null
        // In some flows in to this function, we retrieve the task record and hold on to it
        // without a lock before calling back in to here...  so the task at this point may
        // not actually be in recents.  Check for that, and if it isn't in recents just
        // consider it invalid.
        // 在进入此函数的某些流程中,我们检索任务记录并在不加锁的情况下保留它,然后再调用此处...因此此时的任务实际上可能不是最近的。 检查它,如果它不是最近的,就认为它无效。
        if (inTask != null && !inTask.inRecents) {// 为false,不走进去
            Slog.w(TAG, "Starting activity in task not in recents: " + inTask);
            mInTask = null;
        }

        mStartFlags = startFlags;
        // If the onlyIfNeeded flag is set, then we can do this if the activity being launched
        // is the same as the one making the call...  or, as a special case, if we do not know
        // the caller then we count the current top activity as the caller.
        if ((startFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {// 为false,不走进去
            ActivityRecord checkedCaller = sourceRecord;
            if (checkedCaller == null) {
                checkedCaller = mRootActivityContainer.getTopDisplayFocusedStack()
                        .topRunningNonDelayedActivityLocked(mNotTop);
            }
            if (!checkedCaller.mActivityComponent.equals(r.mActivityComponent)) {
                // Caller is not the same as launcher, so always needed.
                mStartFlags &= ~START_FLAG_ONLY_IF_NEEDED;
            }
        }

        mNoAnimation = (mLaunchFlags & FLAG_ACTIVITY_NO_ANIMATION) != 0;

        if (mRestrictedBgActivity && !mService.isBackgroundActivityStartsEnabled()) {// 为false,不走进去
            mAvoidMoveToFront = true;
            mDoResume = false;
        }
    }

3.11 setTaskFromReuseOrCreateNewTask-创建taskrecord

    private int setTaskFromReuseOrCreateNewTask(TaskRecord taskToAffiliate) {
        if (mRestrictedBgActivity && (mReuseTask == null || !mReuseTask.containsAppUid(mCallingUid))
                && handleBackgroundActivityAbort(mStartActivity)) {// false,不走进去
            return START_ABORTED;
        }
// 获取focusstack
        mTargetStack = computeStackFocus(mStartActivity, true, mLaunchFlags, mOptions);

        // Do no move the target stack to front yet, as we might bail if
        // isLockTaskModeViolation fails below.

        if (mReuseTask == null) {
            final boolean toTop = !mLaunchTaskBehind && !mAvoidMoveToFront;// true
            // 创建taskrecord
            final TaskRecord task = mTargetStack.createTaskRecord(
                    mSupervisor.getNextTaskIdForUserLocked(mStartActivity.mUserId),
                    mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
                    mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
                    mVoiceInteractor, toTop, mStartActivity, mSourceRecord, mOptions);
            // ??
            addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
            updateBounds(mStartActivity.getTaskRecord(), mLaunchParams.mBounds);

            if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Starting new activity " + mStartActivity
                    + " in new task " + mStartActivity.getTaskRecord());
        } else {
            addOrReparentStartingActivity(mReuseTask, "setTaskFromReuseOrCreateNewTask");
        }

        if (taskToAffiliate != null) {// 为false,不走进去
            mStartActivity.setTaskToAffiliateWith(taskToAffiliate);
        }

        if (mService.getLockTaskController().isLockTaskModeViolation(
                mStartActivity.getTaskRecord())) {// 为false,不走进去
            Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
            return START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }

        if (mDoResume) {// true
            // mTargetStack这个是啥值?将stack移动到最前面
            mTargetStack.moveToFront("reuseOrNewTask");
        }
        return START_SUCCESS;
    }

3.12 computeStackFocus-创建activitystack

    private ActivityStack computeStackFocus(ActivityRecord r, boolean newTask, int launchFlags,
            ActivityOptions aOptions) {
        final TaskRecord task = r.getTaskRecord();// null
        // 走这里,创建activitystack
        ActivityStack stack = getLaunchStack(r, launchFlags, task, aOptions);
        if (stack != null) {// 不为null,直接返回了
            return stack;
        }

        final ActivityStack currentStack = task != null ? task.getStack() : null;
        final ActivityStack focusedStack = mRootActivityContainer.getTopDisplayFocusedStack();
        if (currentStack != null) {
            if (focusedStack != currentStack) {
                if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
                        "computeStackFocus: Setting " + "focused stack to r=" + r
                                + " task=" + task);
            } else {
                if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
                        "computeStackFocus: Focused stack already=" + focusedStack);
            }
            return currentStack;
        }

        if (canLaunchIntoFocusedStack(r, newTask)) {
            if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
                    "computeStackFocus: Have a focused stack=" + focusedStack);
            return focusedStack;
        }

        if (mPreferredDisplayId != DEFAULT_DISPLAY) {
            // Try to put the activity in a stack on a secondary display.
            stack = mRootActivityContainer.getValidLaunchStackOnDisplay(
                    mPreferredDisplayId, r, aOptions, mLaunchParams);
            if (stack == null) {
                // If source display is not suitable - look for topmost valid stack in the system.
                if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
                        "computeStackFocus: Can't launch on mPreferredDisplayId="
                                + mPreferredDisplayId + ", looking on all displays.");
                stack = mRootActivityContainer.getNextValidLaunchStack(r, mPreferredDisplayId);
            }
        }
        if (stack == null) {
            stack = mRootActivityContainer.getLaunchStack(r, aOptions, task, ON_TOP);
        }
        if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS, "computeStackFocus: New stack r="
                + r + " stackId=" + stack.mStackId);
        return stack;
    }

3.13 getLaunchStack-创建activitystack

    private ActivityStack getLaunchStack(ActivityRecord r, int launchFlags, TaskRecord task,            ActivityOptions aOptions) {        // We are reusing a task, keep the stack!        if (mReuseTask != null) {// 为null,不走进去            return mReuseTask.getStack();        }        if (((launchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) == 0)                 || mPreferredDisplayId != DEFAULT_DISPLAY) {// 走进去            final boolean onTop = aOptions == null || !aOptions.getAvoidMoveToFront();            final ActivityStack stack =// 创建activitystack                    mRootActivityContainer.getLaunchStack(r, aOptions, task, onTop, mLaunchParams);            return stack;        }        // Otherwise handle adjacent launch.        final ActivityStack focusedStack = mRootActivityContainer.getTopDisplayFocusedStack();        // The parent activity doesn't want to launch the activity on top of itself, but        // instead tries to put it onto other side in side-by-side mode.        final ActivityStack parentStack = task != null ? task.getStack(): focusedStack;        if (parentStack != focusedStack) {            // If task's parent stack is not focused - use it during adjacent launch.            return parentStack;        } else {            if (focusedStack != null && task == focusedStack.topTask()) {                // If task is already on top of focused stack - use it. We don't want to move the                // existing focused task to adjacent stack, just deliver new intent in this case.                return focusedStack;            }            if (parentStack != null && parentStack.inSplitScreenPrimaryWindowingMode()) {                // If parent was in docked stack, the natural place to launch another activity                // will be fullscreen, so it can appear alongside the docked window.                final int activityType =                        mRootActivityContainer.resolveActivityType(r, mOptions, task);                return parentStack.getDisplay().getOrCreateStack(                        WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, activityType, ON_TOP);            } else {                // If the parent is not in the docked stack, we check if there is docked window                // and if yes, we will launch into that stack. If not, we just put the new                // activity into parent's stack, because we can't find a better place.                final ActivityStack dockedStack =                        mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();                if (dockedStack != null && !dockedStack.shouldBeVisible(r)) {                    // There is a docked stack, but it isn't visible, so we can't launch into that.                    return mRootActivityContainer.getLaunchStack(r, aOptions, task, ON_TOP);                } else {                    return dockedStack;                }            }        }    }

4. ActivityStackSupervisor类

frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java

这个类已经成为一个垃圾场。 让我们将与层次结构相关的事物移至 RootWindowContainer 将与活动生命周期相关的事物移至一个名为 ActivityLifeCycler 的新类 将接口事物移至 ActivityTaskManagerService。 其他文件的所有其他小东西。

4.1 resolveIntent-调用PMS来解析intent,获取到了activityInfo和applicationInfo的信息

    ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,            int filterCallingUid) {        try {            Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "resolveIntent");            int modifiedFlags = flags                    | PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS;            if (intent.isWebIntent()                        || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {                modifiedFlags |= PackageManager.MATCH_INSTANT;            }            // In order to allow cross-profile lookup, we clear the calling identity here.            // Note the binder identity won't affect the result, but filterCallingUid will.            // Cross-user/profile call check are done at the entry points            // (e.g. AMS.startActivityAsUser).            final long token = Binder.clearCallingIdentity();            try {// 这里调用PMS来解析intent,获取到了activityInfo和applicationInfo的信息                return mService.getPackageManagerInternalLocked().resolveIntent(                        intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);            } finally {                Binder.restoreCallingIdentity(token);            }        } finally {            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);        }    }

4.2 resolveActivity-根据resolveInfo信息得到ActivityInfo信息

    ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,            ProfilerInfo profilerInfo) {        final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;        if (aInfo != null) {            // Store the found target back into the intent, because now that            // we have it we never want to do this again.  For example, if the            // user navigates back to this point in the history, we should            // always restart the exact same activity.            // 将intent中的component设置为找到的resolveinfo信息            intent.setComponent(new ComponentName(                    aInfo.applicationInfo.packageName, aInfo.name));            // Don't debug things in the system process            // processName为com.android.gallery3d,debug相关的,system进程不进行debug            if (!aInfo.processName.equals("system")) {                // startFlags为0,profilerinfo为null,所以不走下面的                if ((startFlags & (START_FLAG_DEBUG | START_FLAG_NATIVE_DEBUGGING                        | START_FLAG_TRACK_ALLOCATION)) != 0 || profilerInfo != null) {                     // Mimic an AMS synchronous call by passing a message to AMS and wait for AMS                     // to notify us that the task has completed.                     // TODO(b/80414790) look into further untangling for the situation where the                     // caller is on the same thread as the handler we are posting to.                    synchronized (mService.mGlobalLock) {                        // Post message to AMS.                        final Message msg = PooledLambda.obtainMessage(                                ActivityManagerInternal::setDebugFlagsForStartingActivity,                                mService.mAmInternal, aInfo, startFlags, profilerInfo,                                mService.mGlobalLock);                        mService.mH.sendMessage(msg);                        try {                            mService.mGlobalLock.wait();                        } catch (InterruptedException ignore) {                        }                    }                }            }            final String intentLaunchToken = intent.getLaunchToken();            // 大家都为null            if (aInfo.launchToken == null && intentLaunchToken != null) {                aInfo.launchToken = intentLaunchToken;            }        }// 返回activityInfo信息        return aInfo;    }

5. RootActivityContainer类-activity容器的根节点

./frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java

活动容器的根节点。 TODO:这个类主要是临时的,用于将 ActivityStackSupervisor.java 中的东西分开。 目的是将其与 RootWindowContainer.java 合并,作为统一层次结构的一部分。

5.1 getTopDisplayFocusedStack-获取根activitystack的信息

    ActivityStack getTopDisplayFocusedStack() {        for (int i = mActivityDisplays.size() - 1; i >= 0; --i) {            final ActivityStack focusedStack = mActivityDisplays.get(i).getFocusedStack();            if (focusedStack != null) {                return focusedStack;            }        }        return null;    }

5.2 resumeFocusedStacksTopActivities-启动并显示activity

   boolean resumeFocusedStacksTopActivities(            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {        if (!mStackSupervisor.readyToResume()) {// 为false,不走进去            return false;        }	        boolean result = false;        if (targetStack != null && (targetStack.isTopStackOnDisplay()                || getTopDisplayFocusedStack() == targetStack)) {            // 1. 走这里,result为true            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);        }// 走这里        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {            boolean resumedOnDisplay = false;            // 先获取display            final ActivityDisplay display = mAct	ivityDisplays.get(displayNdx);            for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {                // 然后获取activitystack                final ActivityStack stack = display.getChildAt(stackNdx);                // 之后获取activityRecord                final ActivityRecord topRunningActivity = stack.topRunningActivityLocked();                // topRunningActivity为ActivityRecord{6ff8725 u0 com.android.gallery3d/.app.GalleryActivity t20}                if (!stack.isFocusableAndVisible() || topRunningActivity == null) {                    continue;                }                if (stack == targetStack) {                    // Simply update the result for targetStack because the targetStack had                    // already resumed in above. We don't want to resume it again, especially in                    // some cases, it would cause a second launch failure if app process was dead.     // 只需更新 targetStack 的结果,因为 targetStack 已经在上面恢复。 我们不想再次恢复它,特别是在某些情况下,如果应用程序进程死了会导致第二次启动失败。                    resumedOnDisplay |= result;// resumedOnDisplay为true                    // 这里跳过                    continue;                }                if (display.isTopStack(stack) && topRunningActivity.isState(RESUMED)) {                    // Kick off any lingering app transitions form the MoveTaskToFront operation,                    // but only consider the top task and stack on that display.                    stack.executeAppTransition(targetOptions);                } else {                    resumedOnDisplay |= topRunningActivity.makeActiveIfNeeded(target);                }            }            if (!resumedOnDisplay) {                // In cases when there are no valid activities (e.g. device just booted or launcher                // crashed) it's possible that nothing was resumed on a display. Requesting resume                // of top activity in focused stack explicitly will make sure that at least home                // activity is started and resumed, and no recursion occurs.                final ActivityStack focusedStack = display.getFocusedStack();                if (focusedStack != null) {                    focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);                }            }        }        return result;    }

5.3 getLaunchStack-创建activitystack

    <T extends ActivityStack> T getLaunchStack(@Nullable ActivityRecord r,            @Nullable ActivityOptions options, @Nullable TaskRecord candidateTask, boolean onTop,            @Nullable LaunchParamsController.LaunchParams launchParams) {        int taskId = INVALID_TASK_ID;        int displayId = INVALID_DISPLAY;        //Rect bounds = null;        // We give preference to the launch preference in activity options.        if (options != null) {// 不为null,走进去            taskId = options.getLaunchTaskId();            displayId = options.getLaunchDisplayId();        }        // First preference for stack goes to the task Id set in the activity options. Use the stack        // associated with that if possible.        if (taskId != INVALID_TASK_ID) {// id为-1,不走进去            // Temporarily set the task id to invalid in case in re-entry.            options.setLaunchTaskId(INVALID_TASK_ID);            final TaskRecord task = anyTaskForId(taskId,                    MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, options, onTop);            options.setLaunchTaskId(taskId);            if (task != null) {                return task.getStack();            }        }        final int activityType = resolveActivityType(r, options, candidateTask);        T stack;        // Next preference for stack goes to the display Id set the candidate display.        if (launchParams != null && launchParams.mPreferredDisplayId != INVALID_DISPLAY) {            displayId = launchParams.mPreferredDisplayId;// 0        }        if (displayId != INVALID_DISPLAY && canLaunchOnDisplay(r, displayId)) {            if (r != null) {                stack = (T) getValidLaunchStackOnDisplay(displayId, r, candidateTask, options,                        launchParams);// 返回为null                if (stack != null) {                    return stack;                }            }            final ActivityDisplay display = getActivityDisplayOrCreate(displayId);            if (display != null) {                // 这里创建activitystack                stack = display.getOrCreateStack(r, options, candidateTask, activityType, onTop);                if (stack != null) {                    // 在这里返回                    return stack;                }            }        }        // Give preference to the stack and display of the input task and activity if they match the        // mode we want to launch into.        stack = null;        ActivityDisplay display = null;        if (candidateTask != null) {            stack = candidateTask.getStack();        }        if (stack == null && r != null) {            stack = r.getActivityStack();        }        if (stack != null) {            display = stack.getDisplay();            if (display != null && canLaunchOnDisplay(r, display.mDisplayId)) {                int windowingMode = launchParams != null ? launchParams.mWindowingMode                        : WindowConfiguration.WINDOWING_MODE_UNDEFINED;                if (windowingMode == WindowConfiguration.WINDOWING_MODE_UNDEFINED) {                    windowingMode = display.resolveWindowingMode(r, options, candidateTask,                            activityType);                }                if (stack.isCompatible(windowingMode, activityType)) {                    return stack;                }                if (windowingMode == WINDOWING_MODE_FULLSCREEN_OR_SPLIT_SCREEN_SECONDARY                        && display.getSplitScreenPrimaryStack() == stack                        && candidateTask == stack.topTask()) {                    // This is a special case when we try to launch an activity that is currently on                    // top of split-screen primary stack, but is targeting split-screen secondary.                    // In this case we don't want to move it to another stack.                    // TODO(b/78788972): Remove after differentiating between preferred and required                    // launch options.                    return stack;                }            }        }        if (display == null || !canLaunchOnDisplay(r, display.mDisplayId)) {            display = getDefaultDisplay();        }        return display.getOrCreateStack(r, options, candidateTask, activityType, onTop);    }

6. ActivityMetricsLogger类-trace相关的类

./frameworks/base/services/core/java/com/android/server/wm/ActivityMetricsLogger.java

侦听活动启动、转换、可见性更改和窗口绘制回调以确定应用程序启动时间和绘制延迟。 活动指标的真实来源,并为 Tron、logcat、事件日志和 {@link android.app.WaitResult} 提供数据。

7. WindowProcessController类-传递进程状态给WMS

./frameworks/base/services/core/java/com/android/server/wm/WindowProcessController.java

这个类允许 AM 包中的 ProcessRecord 对象以结构化的方式将其状态的重要更改传达给 WM 包。Activity Manager (AM) 包通过ProcessRecord 管理系统中进程的生命周期。 但是,窗口管理器 (WM) 包了解进程及其状态很重要,因为它会影响 WM 管理窗口和活动的方式。 这个类允许 AM 包中的 ProcessRecord 对象以结构化的方式将其状态的重要更改传达给 WM 包。 WM 包还使用 {@link WindowProcessListener} 请求更改 AM 端的进程状态。 请注意,假定对此类的公共调用来自窗口管理器外部,因此在允许继续调用之前,将持有窗口管理器锁并检查适当的权限。

8. ActivityStartInterceptor类

./frameworks/base/services/core/java/com/android/server/wm/ActivityStartInterceptor.java

一个包含 {@link ActivityStarter#startActivityLocked} 的活动拦截逻辑的类,它通过 setStates 初始化,拦截通过intercept 方法发生。 请注意,该类在创建 {@link ActivityManagerService} 时实例化,因此不能保证其他系统服务已经存在。

8.1 intercept-看是否需要对app进行拦截

    /**     * Intercept the launch intent based on various signals. If an interception happened the     * internal variables get assigned and need to be read explicitly by the caller.     *     * @return true if an interception occurred     */    boolean intercept(Intent intent, ResolveInfo rInfo, ActivityInfo aInfo, String resolvedType,            TaskRecord inTask, int callingPid, int callingUid, ActivityOptions activityOptions) {        mUserManager = UserManager.get(mServiceContext);        mIntent = intent;        mCallingPid = callingPid;        mCallingUid = callingUid;        mRInfo = rInfo;        mAInfo = aInfo;        mResolvedType = resolvedType;        mInTask = inTask;        mActivityOptions = activityOptions;        if (interceptSuspendedPackageIfNeeded()) {// suspended标志,返回false            // Skip the rest of interceptions as the package is suspended by device admin so            // no user action can undo this.            return true;        }        if (interceptQuietProfileIfNeeded()) {// 安静模式,返回false            // If work profile is turned off, skip the work challenge since the profile can only            // be unlocked when profile's user is running.            return true;        }        // 如果应用程序有与之相关的“有害应用程序”警告,我们应该在发出工作挑战之前要求卸载。        if (interceptHarmfulAppIfNeeded()) {// false            // If the app has a "harmful app" warning associated with it, we should ask to uninstall            // before issuing the work challenge.            return true;        }// 如果需要,创建一个意图来拦截当前活动,并从 Confirm Credentials 开始。        // 屏幕解锁拦截,是否对app进行加密了        return interceptWorkProfileChallengeIfNeeded();    }

9. ActivityRecord类

./frameworks/base/services/core/java/com/android/server/wm/ActivityRecord.java

历史堆栈中的一个条目,代表一个活动。

9.1 ActivityRecord类-构造函数

// 赋值操作    ActivityRecord(ActivityTaskManagerService _service, WindowProcessController _caller,            int _launchedFromPid, int _launchedFromUid, String _launchedFromPackage, Intent _intent,            String _resolvedType, ActivityInfo aInfo, Configuration _configuration,            ActivityRecord _resultTo, String _resultWho, int _reqCode, boolean _componentSpecified,            boolean _rootVoiceInteraction, ActivityStackSupervisor supervisor,            ActivityOptions options, ActivityRecord sourceRecord) {        mAtmService = _service;        mRootActivityContainer = _service.mRootActivityContainer;        appToken = new Token(this, _intent);        info = aInfo;        launchedFromPid = _launchedFromPid;        launchedFromUid = _launchedFromUid;        launchedFromPackage = _launchedFromPackage;        mUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);        intent = _intent;        shortComponentName = _intent.getComponent().flattenToShortString();        resolvedType = _resolvedType;        componentSpecified = _componentSpecified;        rootVoiceInteraction = _rootVoiceInteraction;        mLastReportedConfiguration = new MergedConfiguration(_configuration);        resultTo = _resultTo;        resultWho = _resultWho;        requestCode = _reqCode;        setState(INITIALIZING, "ActivityRecord ctor");        frontOfTask = false;        launchFailed = false;        stopped = false;        delayedResume = false;        finishing = false;        deferRelaunchUntilPaused = false;        keysPaused = false;        inHistory = false;        visible = false;        nowVisible = false;        mDrawn = false;        idle = false;        hasBeenLaunched = false;        mStackSupervisor = supervisor;        // This starts out true, since the initial state of an activity is that we have everything,        // and we shouldn't never consider it lacking in state to be removed if it dies.        haveState = true;        // If the class name in the intent doesn't match that of the target, this is        // probably an alias. We have to create a new ComponentName object to keep track        // of the real activity name, so that FLAG_ACTIVITY_CLEAR_TOP is handled properly.        if (aInfo.targetActivity == null                || (aInfo.targetActivity.equals(_intent.getComponent().getClassName())                && (aInfo.launchMode == LAUNCH_MULTIPLE                || aInfo.launchMode == LAUNCH_SINGLE_TOP))) {            mActivityComponent = _intent.getComponent();        } else {            mActivityComponent = new ComponentName(aInfo.packageName, aInfo.targetActivity);        }        taskAffinity = aInfo.taskAffinity;        stateNotNeeded = (aInfo.flags & FLAG_STATE_NOT_NEEDED) != 0;        appInfo = aInfo.applicationInfo;        nonLocalizedLabel = aInfo.nonLocalizedLabel;        labelRes = aInfo.labelRes;        if (nonLocalizedLabel == null && labelRes == 0) {            ApplicationInfo app = aInfo.applicationInfo;            nonLocalizedLabel = app.nonLocalizedLabel;            labelRes = app.labelRes;        }        icon = aInfo.getIconResource();        logo = aInfo.getLogoResource();        theme = aInfo.getThemeResource();        realTheme = theme;        if (realTheme == 0) {            realTheme = aInfo.applicationInfo.targetSdkVersion < HONEYCOMB                    ? android.R.style.Theme : android.R.style.Theme_Holo;        }        if ((aInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {            windowFlags |= LayoutParams.FLAG_HARDWARE_ACCELERATED;        }        if ((aInfo.flags & FLAG_MULTIPROCESS) != 0 && _caller != null                && (aInfo.applicationInfo.uid == SYSTEM_UID                    || aInfo.applicationInfo.uid == _caller.mInfo.uid)) {            processName = _caller.mName;        } else {            processName = aInfo.processName;        }        if ((aInfo.flags & FLAG_EXCLUDE_FROM_RECENTS) != 0) {            intent.addFlags(FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);        }        packageName = aInfo.applicationInfo.packageName;        launchMode = aInfo.launchMode;        Entry ent = AttributeCache.instance().get(packageName,                realTheme, com.android.internal.R.styleable.Window, mUserId);        if (ent != null) {            fullscreen = !ActivityInfo.isTranslucentOrFloating(ent.array);            hasWallpaper = ent.array.getBoolean(R.styleable.Window_windowShowWallpaper, false);            noDisplay = ent.array.getBoolean(R.styleable.Window_windowNoDisplay, false);        } else {            hasWallpaper = false;            noDisplay = false;        }        setActivityType(_componentSpecified, _launchedFromUid, _intent, options, sourceRecord);        immersive = (aInfo.flags & FLAG_IMMERSIVE) != 0;        requestedVrComponent = (aInfo.requestedVrComponent == null) ?                null : ComponentName.unflattenFromString(aInfo.requestedVrComponent);        mShowWhenLocked = (aInfo.flags & FLAG_SHOW_WHEN_LOCKED) != 0;        mInheritShownWhenLocked = (aInfo.privateFlags & FLAG_INHERIT_SHOW_WHEN_LOCKED) != 0;        mTurnScreenOn = (aInfo.flags & FLAG_TURN_SCREEN_ON) != 0;        mRotationAnimationHint = aInfo.rotationAnimation;        lockTaskLaunchMode = aInfo.lockTaskLaunchMode;        if (appInfo.isPrivilegedApp() && (lockTaskLaunchMode == LOCK_TASK_LAUNCH_MODE_ALWAYS                || lockTaskLaunchMode == LOCK_TASK_LAUNCH_MODE_NEVER)) {            lockTaskLaunchMode = LOCK_TASK_LAUNCH_MODE_DEFAULT;        }        if (options != null) {            pendingOptions = options;            mLaunchTaskBehind = options.getLaunchTaskBehind();            final int rotationAnimation = pendingOptions.getRotationAnimationHint();            // Only override manifest supplied option if set.            if (rotationAnimation >= 0) {                mRotationAnimationHint = rotationAnimation;            }            final PendingIntent usageReport = pendingOptions.getUsageTimeReport();            if (usageReport != null) {                appTimeTracker = new AppTimeTracker(usageReport);            }            final boolean useLockTask = pendingOptions.getLockTaskMode();            if (useLockTask && lockTaskLaunchMode == LOCK_TASK_LAUNCH_MODE_DEFAULT) {                lockTaskLaunchMode = LOCK_TASK_LAUNCH_MODE_IF_WHITELISTED;            }            // Gets launch display id from options. It returns INVALID_DISPLAY if not set.            mHandoverLaunchDisplayId = options.getLaunchDisplayId();        }    }

9.2 createAppWindowToken-创建app window token

    void createAppWindowToken() {
        if (mAppWindowToken != null) {
            throw new IllegalArgumentException("App Window Token=" + mAppWindowToken
                    + " already created for r=" + this);
        }

        inHistory = true;

        // TODO(b/36505427): Maybe this call should be moved inside updateOverrideConfiguration()
        task.updateOverrideConfigurationFromLaunchBounds();
        // Make sure override configuration is up-to-date before using to create window controller.
        updateOverrideConfiguration();

        // TODO: remove after unification
        mAppWindowToken = mAtmService.mWindowManager.mRoot.getAppWindowToken(appToken.asBinder());
        if (mAppWindowToken != null) {
            // TODO: Should this throw an exception instead?
            Slog.w(TAG, "Attempted to add existing app token: " + appToken);
        } else {
            final Task container = task.getTask();
            if (container == null) {
                throw new IllegalArgumentException("createAppWindowToken: invalid task =" + task);
            }// 创建app window token;new AppWindowToken
            mAppWindowToken = createAppWindow(mAtmService.mWindowManager, appToken,
                    task.voiceSession != null, container.getDisplayContent(),
                    ActivityTaskManagerService.getInputDispatchingTimeoutLocked(this)
                            * 1000000L, fullscreen,
                    (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0, appInfo.targetSdkVersion,
                    info.screenOrientation, mRotationAnimationHint,
                    mLaunchTaskBehind, isAlwaysFocusable());
            if (DEBUG_TOKEN_MOVEMENT || DEBUG_ADD_REMOVE) {
                Slog.v(TAG, "addAppToken: "
                        + mAppWindowToken + " task=" + container + " at "
                        + Integer.MAX_VALUE);
            }
            container.addChild(mAppWindowToken, Integer.MAX_VALUE /* add on top */);
        }

        task.addActivityToTop(this);

        // When an activity is started directly into a split-screen fullscreen stack, we need to
        // update the initial multi-window modes so that the callbacks are scheduled correctly when
        // the user leaves that mode.
        mLastReportedMultiWindowMode = inMultiWindowMode();
        mLastReportedPictureInPictureMode = inPinnedWindowingMode();
    }

9.3 checkEnterPictureInPictureState-检查上一个activity是否进入画中画模式

    boolean checkEnterPictureInPictureState(String caller, boolean beforeStopping) {
        // 此活动是否支持画中画多窗口并可以放入固定堆栈。
        if (!supportsPictureInPicture()) {// 为true,走进去
            return false;// 返回false
        }

        // Check app-ops and see if PiP is supported for this package
        if (!checkEnterPictureInPictureAppOpsState()) {
            return false;
        }

        // Check to see if we are in VR mode, and disallow PiP if so
        if (mAtmService.shouldDisableNonVrUiLocked()) {
            return false;
        }

        boolean isKeyguardLocked = mAtmService.isKeyguardLocked();
        boolean isCurrentAppLocked =
                mAtmService.getLockTaskModeState() != LOCK_TASK_MODE_NONE;
        final ActivityDisplay display = getDisplay();
        boolean hasPinnedStack = display != null && display.hasPinnedStack();
        // Don't return early if !isNotLocked, since we want to throw an exception if the activity
        // is in an incorrect state
        boolean isNotLockedOrOnKeyguard = !isKeyguardLocked && !isCurrentAppLocked;

        // We don't allow auto-PiP when something else is already pipped.
        if (beforeStopping && hasPinnedStack) {
            return false;
        }

        switch (mState) {
            case RESUMED:
                // When visible, allow entering PiP if the app is not locked.  If it is over the
                // keyguard, then we will prompt to unlock in the caller before entering PiP.
                return !isCurrentAppLocked &&
                        (supportsEnterPipOnTaskSwitch || !beforeStopping);
            case PAUSING:
            case PAUSED:
                // When pausing, then only allow enter PiP as in the resume state, and in addition,
                // require that there is not an existing PiP activity and that the current system
                // state supports entering PiP
                return isNotLockedOrOnKeyguard && !hasPinnedStack
                        && supportsEnterPipOnTaskSwitch;
            case STOPPING:
                // When stopping in a valid state, then only allow enter PiP as in the pause state.
                // Otherwise, fall through to throw an exception if the caller is trying to enter
                // PiP in an invalid stopping state.
                if (supportsEnterPipOnTaskSwitch) {
                    return isNotLockedOrOnKeyguard && !hasPinnedStack;
                }
            default:
                return false;
        }
    }

10. WindowManagerService类

./frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java

11.1 deferSurfaceLayout-推迟布局传递

// 开始推迟布局传递。 在进行多次更改时很有用,但为了优化性能,只应完成一次布局传递。 这可以被多次调用,一旦最后一个调用者调用了 {@link #continueSurfaceLayout},布局就会恢复。    void deferSurfaceLayout() {        mWindowPlacerLocked.deferLayout();    }

11. ActivityStack类-管理单个栈的activities的状态

./frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java

单个活动堆栈的状态和管理。

11.1 createTaskRecord-创建taskrecord

    TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,            boolean toTop, ActivityRecord activity, ActivityRecord source,            ActivityOptions options) {        // 创建taskrecord        final TaskRecord task = TaskRecord.create(                mService, taskId, info, intent, voiceSession, voiceInteractor);        // add the task to stack first, mTaskPositioner might need the stack association        // 首先将任务添加到堆栈,mTaskPositioner 可能需要堆栈关联        addTask(task, toTop, "createTaskRecord");        final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY;        final boolean isLockscreenShown = mService.mStackSupervisor.getKeyguardController()                .isKeyguardOrAodShowing(displayId);        if (!mStackSupervisor.getLaunchParamsController()                .layoutTask(task, info.windowLayout, activity, source, options)                && !matchParentBounds() && task.isResizeable() && !isLockscreenShown) {            task.updateOverrideConfiguration(getRequestedOverrideBounds());        }        // 创建task对象,并添加到stack中        task.createTask(toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);        return task;    }

11.2 startActivityLocked-启动activity

    void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,            boolean newTask, boolean keepCurTransition, ActivityOptions options) {        TaskRecord rTask = r.getTaskRecord();        final int taskId = rTask.taskId;        final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();        // mLaunchTaskBehind tasks get placed at the back of the task stack.        if (!r.mLaunchTaskBehind && allowMoveToFront                && (taskForIdLocked(taskId) == null || newTask)) {            // Last activity in task had been removed or ActivityManagerService is reusing task.            // Insert or replace.            // Might not even be in.            // 1. 添加task到mTaskHistory中            insertTaskAtTop(rTask, r);        }        TaskRecord task = null;        if (!newTask) {// 为false,不走进去            // If starting in an existing task, find where that is...            boolean startIt = true;            for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {                task = mTaskHistory.get(taskNdx);                if (task.getTopActivity() == null) {                    // All activities in task are finishing.                    continue;                }                if (task == rTask) {                    // Here it is!  Now, if this is not yet visible to the                    // user, then just add it without starting; it will                    // get started when the user navigates back to it.                    if (!startIt) {                        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task "                                + task, new RuntimeException("here").fillInStackTrace());                        r.createAppWindowToken();                        ActivityOptions.abort(options);                        return;                    }                    break;                } else if (task.numFullscreen > 0) {                    startIt = false;                }            }        }        // Place a new activity at top of stack, so it is next to interact with the user.        // If we are not placing the new activity frontmost, we do not want to deliver the        // onUserLeaving callback to the actual frontmost activity        final TaskRecord activityTask = r.getTaskRecord();        if (task == activityTask && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {// 为false,不走进去            mStackSupervisor.mUserLeaving = false;            if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,                    "startActivity() behind front, mUserLeaving=false");        }        task = activityTask;        // Slot the activity into the history stack and proceed        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task,                new RuntimeException("here").fillInStackTrace());        // TODO: Need to investigate if it is okay for the controller to already be created by the        // time we get to this point. I think it is, but need to double check.        // Use test in b/34179495 to trace the call path.        if (r.mAppWindowToken == null) {            // 2. 创建AppWindowToken            r.createAppWindowToken();        }        task.setFrontOfTask();        // The transition animation and starting window are not needed if {@code allowMoveToFront}        // is false, because the activity won't be visible.        // 如果 {@code allowMoveToFront} 为 false,则不需要过渡动画和启动窗口,因为活动将不可见。        if ((!isHomeOrRecentsStack() || numActivities() > 0) && allowMoveToFront) {// 为true,走进去            // 下面和显示动画相关的            final DisplayContent dc = getDisplay().mDisplayContent;            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,                    "Prepare open transition: starting " + r);            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {                dc.prepareAppTransition(TRANSIT_NONE, keepCurTransition);                mStackSupervisor.mNoAnimActivities.add(r);            } else {                int transit = TRANSIT_ACTIVITY_OPEN;// 走这里,有动画的                if (newTask) {                    if (r.mLaunchTaskBehind) {                        transit = TRANSIT_TASK_OPEN_BEHIND;                    } else if (getDisplay().isSingleTaskInstance()) {                        transit = TRANSIT_SHOW_SINGLE_TASK_DISPLAY;                    } else {                        // If a new task is being launched, then mark the existing top activity as                        // supporting picture-in-picture while pausing only if the starting activity                        // would not be considered an overlay on top of the current activity                        // (eg. not fullscreen, or the assistant)                        if (canEnterPipOnTaskSwitch(focusedTopActivity,                                null /* toFrontTask */, r, options)) {                            focusedTopActivity.supportsEnterPipOnTaskSwitch = true;// 走这里,为true                        }                        transit = TRANSIT_TASK_OPEN;                    }                }                // 3. 准备应用的动画                dc.prepareAppTransition(transit, keepCurTransition);                mStackSupervisor.mNoAnimActivities.remove(r);            }            boolean doShow = true;            if (newTask) {                // Even though this activity is starting fresh, we still need                // to reset it to make sure we apply affinities to move any                // existing activities from other tasks in to it.                // If the caller has requested that the target task be                // reset, then do so.                // 即使此活动重新开始,我们仍然需要重置它以确保我们应用关联性将任何现有活动从其他任务移入其中。 如果调用者已请求重置目标任务,则执行此操作。                if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {                    resetTaskIfNeededLocked(r, r);// 走这里                    doShow = topRunningNonDelayedActivityLocked(null) == r;                }            } else if (options != null && options.getAnimationType()                    == ActivityOptions.ANIM_SCENE_TRANSITION) {                doShow = false;            }            if (r.mLaunchTaskBehind) {                // Don't do a starting window for mLaunchTaskBehind. More importantly make sure we                // tell WindowManager that r is visible even though it is at the back of the stack.                r.setVisibility(true);                ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);            } else if (SHOW_APP_STARTING_PREVIEW && doShow) {// 走这里                // Figure out if we are transitioning from another activity that is                // "has the same starting icon" as the next one.  This allows the                // window manager to keep the previous window it had previously                // created, if it still had one.                // 弄清楚我们是否正在从与下一个“具有相同起始图标”的另一个活动过渡。 这允许窗口管理器保留它之前创建的前一个窗口,如果它还有一个的话。                TaskRecord prevTask = r.getTaskRecord();                ActivityRecord prev = prevTask.topRunningActivityWithStartingWindowLocked();                if (prev != null) {                    // We don't want to reuse the previous starting preview if:                    // (1) The current activity is in a different task.                    if (prev.getTaskRecord() != prevTask) {                        prev = null;                    }                    // (2) The current activity is already displayed.                    else if (prev.nowVisible) {                        prev = null;                    }                }                // 4. 调用WMS创建窗口相关的                r.showStartingWindow(prev, newTask, isTaskSwitch(r, focusedTopActivity));            }        } else {            // If this is the first activity, don't do any fancy animations,            // because there is nothing for it to animate on top of.            ActivityOptions.abort(options);        }    }

11.3 resumeTopActivityUncheckedLocked

// 确保恢复堆栈中的顶部活动。    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {        if (mInResumeTopActivity) {            // Don't even start recursing.            return false;        }        boolean result = false;        try {            // Protect against recursion.            mInResumeTopActivity = true;            // 1. 走这里,prev为grallary,要启动的activity            result = resumeTopActivityInnerLocked(prev, options);            // When resuming the top activity, it may be necessary to pause the top activity (for            // example, returning to the lock screen. We suppress the normal pause logic in            // {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the            // end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here            // to ensure any necessary pause logic occurs. In the case where the Activity will be            // shown regardless of the lock screen, the call to            // {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.            // 在恢复top Activity时,可能需要暂停top Activity(例如返回锁屏。我们在{@link #resumeTopActivityUncheckedLocked}中抑制了正常的暂停逻辑,因为top Activity是在最后恢复的。我们 在此处再次调用 {@link ActivityStackSupervisor#checkReadyForSleepLocked} 以确保发生任何必要的暂停逻辑。如果无论锁定屏幕如何都会显示 Activity,则跳过对 {@link ActivityStackSupervisor#checkReadyForSleepLocked} 的调用。            final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);            if (next == null || !next.canTurnScreenOn()) {                checkReadyForSleep();            }        } finally {            mInResumeTopActivity = false;        }        return result;    }

11.4 resumeTopActivityInnerLocked

    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        // 系统启动的时候
        if (!mService.isBooting() && !mService.isBooted()) {
            // Not ready yet!
            return false;
        }

        // Find the next top-most activity to resume in this stack that is not finishing and is
        // focusable. If it is not focusable, we will fall into the case below to resume the
        // top activity in the next focusable task.
        // 在此堆栈中找到下一个最顶层的活动,该活动尚未完成且可聚焦。 如果它不是可聚焦的,我们将陷入下面的情况,在下一个可聚焦的任务中恢复最上面的活动。
        // ActivityRecord{121388f u0 com.android.gallery3d/.app.GalleryActivity t16}
        ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

        final boolean hasRunningActivity = next != null;// true

        // TODO: Maybe this entire condition can get removed?
        if (hasRunningActivity && !isAttached()) {
            return false;
        }
// 如果顶部运行的活动下方的任何活动处于 INITIALIZING 状态,并且它们显示了一个启动窗口,则删除该启动窗口。 这种状态下的活动可能永远不会恢复,在这种情况下,起始窗口将被孤立。
        mRootActivityContainer.cancelInitializingActivities();

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        // 记住我们将如何处理这种暂停/恢复情况,并确保状态被重置,但我们最终会继续进行。
        boolean userLeaving = mStackSupervisor.mUserLeaving;
        mStackSupervisor.mUserLeaving = false;

        if (!hasRunningActivity) {
            // There are no activities left in the stack, let's look somewhere else.
            return resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
        }

        next.delayedResume = false;
        // 获取display
        final ActivityDisplay display = getDisplay();

        // If the top activity is the resumed one, nothing to do.
        // 如果顶级活动是恢复的活动,则无事可做。
        if (mResumedActivity == next && next.isState(RESUMED)
                && display.allResumedActivitiesComplete()) {// mResumedActivity为null,则不走进去
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            executeAppTransition(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Top activity resumed " + next);
            return false;
        }
// next的app为null,canResumeByCompat返回true
        if (!next.canResumeByCompat()) {// 为false,不走进去
            return false;
        }

        // If we are sleeping, and there is no resumed activity, and the top
        // activity is paused, well that is the state we want.
        // 如果我们正在睡觉,并且没有恢复的活动,并且顶部活动暂停,那么这就是我们想要的状态。
        if (shouldSleepOrShutDownActivities()
                && mLastPausedActivity == next
                && mRootActivityContainer.allPausedActivitiesComplete()) {// 为false,不走进去
            // If the current top activity may be able to occlude keyguard but the occluded state
            // has not been set, update visibility and check again if we should continue to resume.
            boolean nothingToResume = true;
            if (!mService.mShuttingDown) {
                final boolean canShowWhenLocked = !mTopActivityOccludesKeyguard
                        && next.canShowWhenLocked();
                final boolean mayDismissKeyguard = mTopDismissingKeyguardActivity != next
                        && next.mAppWindowToken != null
                        && next.mAppWindowToken.containsDismissKeyguardWindow();

                if (canShowWhenLocked || mayDismissKeyguard) {
                    ensureActivitiesVisibleLocked(null /* starting */, 0 /* configChanges */,
                            !PRESERVE_WINDOWS);
                    nothingToResume = shouldSleepActivities();
                }
            }
            if (nothingToResume) {
                // Make sure we have executed any pending transitions, since there
                // should be nothing left to do at this point.
                executeAppTransition(options);
                if (DEBUG_STATES) Slog.d(TAG_STATES,
                        "resumeTopActivityLocked: Going to sleep and all paused");
                return false;
            }
        }

        // Make sure that the user who owns this activity is started.  If not,
        // we will just leave it as is because someone should be bringing
        // another user's activities to the top of the stack.
        // 确保拥有此活动的用户已启动。 如果没有,我们将保持原样,因为应该有人将另一个用户的活动带到堆栈的顶部。
        if (!mService.mAmInternal.hasStartedUserState(next.mUserId)) {
            Slog.w(TAG, "Skipping resume of top activity " + next
                    + ": user " + next.mUserId + " is stopped");
            return false;
        }

        // The activity may be waiting for stop, but that is no longer
        // appropriate for it.
        // 活动可能正在等待停止,但这不再适合它。
        mStackSupervisor.mStoppingActivities.remove(next);
        mStackSupervisor.mGoingToSleepActivities.remove(next);
        next.sleeping = false;

        if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resuming " + next);

        // If we are currently pausing an activity, then don't do anything until that is done.
        // 活动可能正在等待停止,但这不再适合它。
        if (!mRootActivityContainer.allPausedActivitiesComplete()) {
            if (DEBUG_SWITCH || DEBUG_PAUSE || DEBUG_STATES) Slog.v(TAG_PAUSE,
                    "resumeTopActivityLocked: Skip resume: some activity pausing.");

            return false;
        }
// 设置与唤醒锁关联的工作源。
        mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);

        boolean lastResumedCanPip = false;
        ActivityRecord lastResumed = null;
        final ActivityStack lastFocusedStack = display.getLastFocusedStack();
        if (lastFocusedStack != null && lastFocusedStack != this) {
            // 走进来
            // So, why aren't we using prev here??? See the param comment on the method. prev doesn't
            // represent the last resumed activity. However, the last focus stack does if it isn't null.
            // 那么,我们为什么不在这里使用 prev ??? 请参阅该方法的参数注释。 prev 不代表上次恢复的活动。 但是,如果最后一个焦点堆栈不为空,则它会执行。
            lastResumed = lastFocusedStack.mResumedActivity;
            if (userLeaving && inMultiWindowMode() && lastFocusedStack.shouldBeVisible(next)) {
                // The user isn't leaving if this stack is the multi-window mode and the last
                // focused stack should still be visible.
                // 如果此堆栈是多窗口模式并且最后一个聚焦的堆栈仍应可见,则用户不会离开。
                if(DEBUG_USER_LEAVING) Slog.i(TAG_USER_LEAVING, "Overriding userLeaving to false"
                        + " next=" + next + " lastResumed=" + lastResumed);
                userLeaving = false;
            }// lastResumed为launcher3;checkenterPicture为检查画中画模式,上一个应用是否可以进入画中画模式
            lastResumedCanPip = lastResumed != null && lastResumed.checkEnterPictureInPictureState(
                    "resumeTopActivity", userLeaving /* beforeStopping */);
        }
        // If the flag RESUME_WHILE_PAUSING is set, then continue to schedule the previous activity
        // to be paused, while at the same time resuming the new resume activity only if the
        // previous activity can't go into Pip since we want to give Pip activities a chance to
        // enter Pip before resuming the next activity.
        // 如果设置了标志 RESUME_WHILE_PAUSING,则继续安排之前的活动暂停,同时只有在之前的活动无法进入 Pip 时才恢复新的恢复活动,因为我们想给 Pip 活动一个进入的机会 在恢复下一个活动之前点一下。
        final boolean resumeWhilePausing = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0
                && !lastResumedCanPip;
// 暂停所有堆栈或仅后堆栈中的所有活动。 这是在恢复新活动之前完成的,并确保先前活动的活动在不再可见的堆栈中或处于固定窗口模式中暂停。 这不会暂停可见堆栈中的活动,因此如果在同一个堆栈/任务中启动了一个活动,那么我们应该明确地暂停该堆栈的顶部活动。
        boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);// true
        if (mResumedActivity != null) {// 为false,不走进去
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            pausing |= startPausingLocked(userLeaving, false, next, false);
        }
        if (pausing && !resumeWhilePausing) {
            // 走进去
            if (DEBUG_SWITCH || DEBUG_STATES) Slog.v(TAG_STATES,
                    "resumeTopActivityLocked: Skip resume: need to start pausing");
            // At this point we want to put the upcoming activity's process
            // at the top of the LRU list, since we know we will be needing it
            // very soon and it would be a waste to let it get killed if it
            // happens to be sitting towards the end.
            // 在这一点上,我们想把即将到来的活动的进程放在 LRU 列表的顶部,因为我们知道我们很快就会需要它,如果它恰好坐在最后,让它被杀死将是一种浪费。
            if (next.attachedToProcess()) {// 为false,不走进去
                next.app.updateProcessInfo(false /* updateServiceConnectionActivities */,
                        true /* activityChange */, false /* updateOomAdj */);
            }
            if (lastResumed != null) {// 为true,走进去
// 通知 AWT 此应用程序正在等待暂停以确定它是否将进入 PIP。 此信息可帮助 AWT 了解应用程序在 WM 端收到信号之前正在暂停的过程中。
                lastResumed.setWillCloseOrEnterPip(true);
            }
            // 这里直接返回了
            return true;
        } else if (mResumedActivity == next && next.isState(RESUMED)
                && display.allResumedActivitiesComplete()) {
            // It is possible for the activity to be resumed when we paused back stacks above if the
            // next activity doesn't have to wait for pause to complete.
            // So, nothing else to-do except:
            // Make sure we have executed any pending transitions, since there
            // should be nothing left to do at this point.
            executeAppTransition(options);
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Top activity resumed (dontWaitForPause) " + next);
            return true;
        }

        // If the most recent activity was noHistory but was only stopped rather
        // than stopped+finished because the device went to sleep, we need to make
        // sure to finish it as we're making a new activity topmost.
        if (shouldSleepActivities() && mLastNoHistoryActivity != null &&
                !mLastNoHistoryActivity.finishing) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "no-history finish of " + mLastNoHistoryActivity + " on new resume");
            requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                    null, "resume-no-history", false);
            mLastNoHistoryActivity = null;
        }

        if (prev != null && prev != next && next.nowVisible) {

            // The next activity is already visible, so hide the previous
            // activity's windows right now so we can show the new one ASAP.
            // We only do this if the previous is finishing, which should mean
            // it is on top of the one being resumed so hiding it quickly
            // is good.  Otherwise, we want to do the normal route of allowing
            // the resumed activity to be shown so we can decide if the
            // previous should actually be hidden depending on whether the
            // new one is found to be full-screen or not.
            if (prev.finishing) {
                prev.setVisibility(false);
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                        "Not waiting for visible to hide: " + prev
                        + ", nowVisible=" + next.nowVisible);
            } else {
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH,
                        "Previous already visible but still waiting to hide: " + prev
                        + ", nowVisible=" + next.nowVisible);
            }

        }

        // Launching this app's activity, make sure the app is no longer
        // considered stopped.
        try {
            AppGlobals.getPackageManager().setPackageStoppedState(
                    next.packageName, false, next.mUserId); /* TODO: Verify if correct userid */
        } catch (RemoteException e1) {
        } catch (IllegalArgumentException e) {
            Slog.w(TAG, "Failed trying to unstop package "
                    + next.packageName + ": " + e);
        }

        // We are starting up the next activity, so tell the window manager
        // that the previous one will be hidden soon.  This way it can know
        // to ignore it when computing the desired screen orientation.
        boolean anim = true;
        final DisplayContent dc = getDisplay().mDisplayContent;
        if (prev != null) {
            if (prev.finishing) {
                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                        "Prepare close transition: prev=" + prev);
                if (mStackSupervisor.mNoAnimActivities.contains(prev)) {
                    anim = false;
                    dc.prepareAppTransition(TRANSIT_NONE, false);
                } else {
                    dc.prepareAppTransition(
                            prev.getTaskRecord() == next.getTaskRecord() ? TRANSIT_ACTIVITY_CLOSE
                                    : TRANSIT_TASK_CLOSE, false);
                }
                prev.setVisibility(false);
            } else {
                if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION,
                        "Prepare open transition: prev=" + prev);
                if (mStackSupervisor.mNoAnimActivities.contains(next)) {
                    anim = false;
                    dc.prepareAppTransition(TRANSIT_NONE, false);
                } else {
                    dc.prepareAppTransition(
                            prev.getTaskRecord() == next.getTaskRecord() ? TRANSIT_ACTIVITY_OPEN
                                    : next.mLaunchTaskBehind ? TRANSIT_TASK_OPEN_BEHIND
                                            : TRANSIT_TASK_OPEN, false);
                }
            }
        } else {
            if (DEBUG_TRANSITION) Slog.v(TAG_TRANSITION, "Prepare open transition: no previous");
            if (mStackSupervisor.mNoAnimActivities.contains(next)) {
                anim = false;
                dc.prepareAppTransition(TRANSIT_NONE, false);
            } else {
                dc.prepareAppTransition(TRANSIT_ACTIVITY_OPEN, false);
            }
        }

        if (anim) {
            next.applyOptionsLocked();
        } else {
            next.clearOptionsLocked();
        }

        mStackSupervisor.mNoAnimActivities.clear();

        if (next.attachedToProcess()) {// next.app为null,所以是还没有创建application的,不走进去
            if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Resume running: " + next
                    + " stopped=" + next.stopped + " visible=" + next.visible);

            // If the previous activity is translucent, force a visibility update of
            // the next activity, so that it's added to WM's opening app list, and
            // transition animation can be set up properly.
            // For example, pressing Home button with a translucent activity in focus.
            // Launcher is already visible in this case. If we don't add it to opening
            // apps, maybeUpdateTransitToWallpaper() will fail to identify this as a
            // TRANSIT_WALLPAPER_OPEN animation, and run some funny animation.
            final boolean lastActivityTranslucent = lastFocusedStack != null
                    && (lastFocusedStack.inMultiWindowMode()
                    || (lastFocusedStack.mLastPausedActivity != null
                    && !lastFocusedStack.mLastPausedActivity.fullscreen));

            // This activity is now becoming visible.
            if (!next.visible || next.stopped || lastActivityTranslucent) {
                next.setVisibility(true);
            }

            // schedule launch ticks to collect information about slow apps.
            next.startLaunchTickingLocked();

            ActivityRecord lastResumedActivity =
                    lastFocusedStack == null ? null : lastFocusedStack.mResumedActivity;
            final ActivityState lastState = next.getState();

            mService.updateCpuStats();

            if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to RESUMED: " + next
                    + " (in existing)");

            next.setState(RESUMED, "resumeTopActivityInnerLocked");

            next.app.updateProcessInfo(false /* updateServiceConnectionActivities */,
                    true /* activityChange */, true /* updateOomAdj */);
            updateLRUListLocked(next);

            // Have the window manager re-evaluate the orientation of
            // the screen based on the new activity order.
            boolean notUpdated = true;

            // Activity should also be visible if set mLaunchTaskBehind to true (see
            // ActivityRecord#shouldBeVisibleIgnoringKeyguard()).
            if (shouldBeVisible(next)) {
                // We have special rotation behavior when here is some active activity that
                // requests specific orientation or Keyguard is locked. Make sure all activity
                // visibilities are set correctly as well as the transition is updated if needed
                // to get the correct rotation behavior. Otherwise the following call to update
                // the orientation may cause incorrect configurations delivered to client as a
                // result of invisible window resize.
                // TODO: Remove this once visibilities are set correctly immediately when
                // starting an activity.
                notUpdated = !mRootActivityContainer.ensureVisibilityAndConfig(next, mDisplayId,
                        true /* markFrozenIfConfigChanged */, false /* deferResume */);
            }

            if (notUpdated) {
                // The configuration update wasn't able to keep the existing
                // instance of the activity, and instead started a new one.
                // We should be all done, but let's just make sure our activity
                // is still at the top and schedule another run if something
                // weird happened.
                ActivityRecord nextNext = topRunningActivityLocked();
                if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG_STATES,
                        "Activity config changed during resume: " + next
                                + ", new next: " + nextNext);
                if (nextNext != next) {
                    // Do over!
                    mStackSupervisor.scheduleResumeTopActivities();
                }
                if (!next.visible || next.stopped) {
                    next.setVisibility(true);
                }
                next.completeResumeLocked();
                return true;
            }

            try {
                final ClientTransaction transaction =
                        ClientTransaction.obtain(next.app.getThread(), next.appToken);
                // Deliver all pending results.
                ArrayList<ResultInfo> a = next.results;
                if (a != null) {
                    final int N = a.size();
                    if (!next.finishing && N > 0) {
                        if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                                "Delivering results to " + next + ": " + a);
                        transaction.addCallback(ActivityResultItem.obtain(a));
                    }
                }

                if (next.newIntents != null) {
                    transaction.addCallback(
                            NewIntentItem.obtain(next.newIntents, true /* resume */));
                }

                // Well the app will no longer be stopped.
                // Clear app token stopped state in window manager if needed.
                next.notifyAppResumed(next.stopped);

                EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY, next.mUserId,
                        System.identityHashCode(next), next.getTaskRecord().taskId,
                        next.shortComponentName);

                next.sleeping = false;
                mService.getAppWarningsLocked().onResumeActivity(next);
                next.app.setPendingUiCleanAndForceProcessStateUpTo(mService.mTopProcessState);
                next.clearOptionsLocked();
                transaction.setLifecycleStateRequest(
                        ResumeActivityItem.obtain(next.app.getReportedProcState(),
                                getDisplay().mDisplayContent.isNextTransitionForward()));
                mService.getLifecycleManager().scheduleTransaction(transaction);

                if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Resumed "
                        + next);
            } catch (Exception e) {
                // Whoops, need to restart this activity!
                if (DEBUG_STATES) Slog.v(TAG_STATES, "Resume failed; resetting state to "
                        + lastState + ": " + next);
                next.setState(lastState, "resumeTopActivityInnerLocked");

                // lastResumedActivity being non-null implies there is a lastStack present.
                if (lastResumedActivity != null) {
                    lastResumedActivity.setState(RESUMED, "resumeTopActivityInnerLocked");
                }

                Slog.i(TAG, "Restarting because process died: " + next);
                if (!next.hasBeenLaunched) {
                    next.hasBeenLaunched = true;
                } else  if (SHOW_APP_STARTING_PREVIEW && lastFocusedStack != null
                        && lastFocusedStack.isTopStackOnDisplay()) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwitch */);
                }
                mStackSupervisor.startSpecificActivityLocked(next, true, false);
                return true;
            }

            // From this point on, if something goes wrong there is no way
            // to recover the activity.
            try {
                next.completeResumeLocked();
            } catch (Exception e) {
                // If any exception gets thrown, toss away this
                // activity and try the next one.
                Slog.w(TAG, "Exception thrown during resume of " + next, e);
                requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
                        "resume-exception", true);
                return true;
            }
        } else {
            // 走这里,创建application
            // Whoops, need to restart this activity!
            if (!next.hasBeenLaunched) {
                next.hasBeenLaunched = true;
            } else {
                if (SHOW_APP_STARTING_PREVIEW) {
                    next.showStartingWindow(null /* prev */, false /* newTask */,
                            false /* taskSwich */);
                }
                if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "Restarting: " + next);
            }
            if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }

        return true;
    }

11.5 topRunningActivityLocked-判断一下是否是finishing的,是否要show,返回activityrecord

    ActivityRecord topRunningActivityLocked(boolean focusableOnly) {
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            // 这里只有TaskRecord{6b21b06 #20 A=com.android.gallery3d U=0 StackId=11 sz=1}
            // 判断一下是否是finishing的,是否要show,返回activityrecord
            ActivityRecord r = mTaskHistory.get(taskNdx).topRunningActivityLocked();
            if (r != null && (!focusableOnly || r.isFocusable())) {
                return r;
            }
        }
        return null;
    }

11.6 ActivityStack构造函数

//     windowingMode为0;activityType为1;onTop为true
ActivityStack(ActivityDisplay display, int stackId, ActivityStackSupervisor supervisor,
            int windowingMode, int activityType, boolean onTop) {
        mStackSupervisor = supervisor;
        mService = supervisor.mService;
        mRootActivityContainer = mService.mRootActivityContainer;
        mHandler = new ActivityStackHandler(supervisor.mLooper);
        mWindowManager = mService.mWindowManager;
        mStackId = stackId;
        mCurrentUser = mService.mAmInternal.getCurrentUserId();
        // Set display id before setting activity and window type to make sure it won't affect
        // stacks on a wrong display.
        mDisplayId = display.mDisplayId;
        setActivityType(activityType);
        createTaskStack(display.mDisplayId, onTop, mTmpRect2);
        setWindowingMode(windowingMode, false /* animate */, false /* showRecents */,
                false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
                true /* creating */);
        display.addChild(this, onTop ? POSITION_TOP : POSITION_BOTTOM);
    }

11.7 insertTaskAtTop-添加task到mTaskHistory中

    private void insertTaskAtTop(TaskRecord task, ActivityRecord starting) {
        // TODO: Better place to put all the code below...may be addTask...
        mTaskHistory.remove(task);
        // Now put task at top.
        final int position = getAdjustedPositionForTask(task, mTaskHistory.size(), starting);
        mTaskHistory.add(position, task);
        updateTaskMovement(task, true);
        positionChildWindowContainerAtTop(task);
    }

12. TaskRecord类

12.1 create-创建taskrecord对象

    static TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info,
            Intent intent, IVoiceInteractionSession voiceSession,
            IVoiceInteractor voiceInteractor) {
        // 调用TaskRecordFactory来创建taskRecord对象,new TaskRecord(service, taskId, info, intent, voiceSession, voiceInteractor);
        return getTaskRecordFactory().create(
                service, taskId, info, intent, voiceSession, voiceInteractor);
    }

12.2 TaskRecord-构造函数

    TaskRecord(ActivityTaskManagerService service, int _taskId, ActivityInfo info, Intent _intent,
            IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) {// 后面两个为null
        mService = service;
        userId = UserHandle.getUserId(info.applicationInfo.uid);
        taskId = _taskId;
        lastActiveTime = SystemClock.elapsedRealtime();
        mAffiliatedTaskId = _taskId;
        voiceSession = _voiceSession;
        voiceInteractor = _voiceInteractor;
        isAvailable = true;
        mActivities = new ArrayList<>();
        mCallingUid = info.applicationInfo.uid;
        mCallingPackage = info.packageName;
        setIntent(_intent, info);	// 设置info和intent
        setMinDimensions(info);
        touchActiveTime();
        mService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity);
    }

12.3 createTask-创建task对象,并添加到stack中

    void createTask(boolean onTop, boolean showForAllUsers) {
        if (mTask != null) {
            throw new IllegalArgumentException("mTask=" + mTask
                    + " already created for task=" + this);
        }

        final Rect bounds = updateOverrideConfigurationFromLaunchBounds();
        final TaskStack stack = getStack().getTaskStack();

        if (stack == null) {
            throw new IllegalArgumentException("TaskRecord: invalid stack=" + mStack);
        }
        EventLog.writeEvent(WM_TASK_CREATED, taskId, stack.mStackId);
        // 创建task对象
        mTask = new Task(taskId, stack, userId, mService.mWindowManager, mResizeMode,
                mSupportsPictureInPicture, lastTaskDescription, this);
        final int position = onTop ? POSITION_TOP : POSITION_BOTTOM;

        if (!mDisplayedBounds.isEmpty()) {
            mTask.setOverrideDisplayedBounds(mDisplayedBounds);
        }
        // We only want to move the parents to the parents if we are creating this task at the
        // top of its stack.
        // 添加task到stack中
        stack.addTask(mTask, position, showForAllUsers, onTop /* moveParents */);
    }

13. Task类

13.1 Task-构造函数

    Task(int taskId, TaskStack stack, int userId, WindowManagerService service, int resizeMode,
            boolean supportsPictureInPicture, TaskDescription taskDescription,
            TaskRecord taskRecord) {
        super(service);
        mTaskId = taskId;
        mStack = stack;
        mUserId = userId;
        mResizeMode = resizeMode;
        mSupportsPictureInPicture = supportsPictureInPicture;
        mTaskRecord = taskRecord;
        if (mTaskRecord != null) {
            // This can be null when we call createTaskInStack in WindowTestUtils. Remove this after
            // unification.
            mTaskRecord.registerConfigurationChangeListener(this);
        }
        setBounds(getRequestedOverrideBounds());
        mTaskDescription = taskDescription;

        // Tasks have no set orientation value (including SCREEN_ORIENTATION_UNSPECIFIED).
        setOrientation(SCREEN_ORIENTATION_UNSET);
    }

14. AppWindowToken类-用来显示窗口的特定应用程序

./frameworks/base/services/core/java/com/android/server/wm/AppWindowToken.java

专门用于显示窗口的特定应用程序(或真正的活动)的 WindowToken 版本。

14.1 AppWindowToken-构造函数

    AppWindowToken(WindowManagerService service, IApplicationToken token,
            ComponentName activityComponent, boolean voiceInteraction, DisplayContent dc,
            long inputDispatchingTimeoutNanos, boolean fullscreen, boolean showForAllUsers,
            int targetSdk, int orientation, int rotationAnimationHint,
            boolean launchTaskBehind, boolean alwaysFocusable,
            ActivityRecord activityRecord) {
        this(service, token, activityComponent, voiceInteraction, dc, fullscreen);
        // TODO: remove after unification
        mActivityRecord = activityRecord;
        mActivityRecord.registerConfigurationChangeListener(this);
        mInputDispatchingTimeoutNanos = inputDispatchingTimeoutNanos;
        mShowForAllUsers = showForAllUsers;
        mTargetSdk = targetSdk;
        mOrientation = orientation;
        mLaunchTaskBehind = launchTaskBehind;
        mAlwaysFocusable = alwaysFocusable;
        mRotationAnimationHint = rotationAnimationHint;

        // Application tokens start out hidden.
        setHidden(true);
        hiddenRequested = true;

        ColorDisplayService.ColorDisplayServiceInternal cds = LocalServices.getService(
                ColorDisplayService.ColorDisplayServiceInternal.class);
        cds.attachColorTransformController(activityRecord.packageName, activityRecord.mUserId,
                new WeakReference<>(mColorTransformController));
    }

15. ActivityDisplay类

./frameworks/base/services/core/java/com/android/server/wm/ActivityDisplay.java

15.1 getOrCreateStack-创建activitystack

    <T extends ActivityStack> T getOrCreateStack(@Nullable ActivityRecord r,
            @Nullable ActivityOptions options, @Nullable TaskRecord candidateTask, int activityType,
            boolean onTop) {
        // First preference is the windowing mode in the activity options if set.
        int windowingMode = (options != null)
                ? options.getLaunchWindowingMode() : WINDOWING_MODE_UNDEFINED;
        // Validate that our desired windowingMode will work under the current conditions.
        // UNDEFINED windowing mode is a valid result and means that the new stack will inherit
        // it's display's windowing mode.
        windowingMode = validateWindowingMode(windowingMode, r, candidateTask, activityType);
        return getOrCreateStack(windowingMode, activityType, onTop);
    }

15.2 getOrCreateStack-创建activitystack

    <T extends ActivityStack> T getOrCreateStack(int windowingMode, int activityType,
            boolean onTop) {
        if (!alwaysCreateStack(windowingMode, activityType)) {// 走进去了
            T stack = getStack(windowingMode, activityType);// 为null
            if (stack != null) {
                return stack;
            }
        }// 这里创建activitystack
        return createStack(windowingMode, activityType, onTop);
    }

15.3 createStack-创建activitystack

    <T extends ActivityStack> T createStack(int windowingMode, int activityType, boolean onTop) {

        if (mSingleTaskInstance && getChildCount() > 0) {// 不是singletask
            // Create stack on default display instead since this display can only contain 1 stack.
            // TODO: Kinda a hack, but better that having the decision at each call point. Hoping
            // this goes away once ActivityView is no longer using virtual displays.
            return mRootActivityContainer.getDefaultDisplay().createStack(
                    windowingMode, activityType, onTop);
        }

        if (activityType == ACTIVITY_TYPE_UNDEFINED) {// 不走进去
            // Can't have an undefined stack type yet...so re-map to standard. Anyone that wants
            // anything else should be passing it in anyways...
            activityType = ACTIVITY_TYPE_STANDARD;
        }

        if (activityType != ACTIVITY_TYPE_STANDARD) {// 不走进去
            // For now there can be only one stack of a particular non-standard activity type on a
            // display. So, get that ignoring whatever windowing mode it is currently in.
            T stack = getStack(WINDOWING_MODE_UNDEFINED, activityType);
            if (stack != null) {
                throw new IllegalArgumentException("Stack=" + stack + " of activityType="
                        + activityType + " already on display=" + this + ". Can't have multiple.");
            }
        }

        if (!isWindowingModeSupported(windowingMode, mService.mSupportsMultiWindow,
                mService.mSupportsSplitScreenMultiWindow,
                mService.mSupportsFreeformWindowManagement, mService.mSupportsPictureInPicture,
                activityType)) {
            throw new IllegalArgumentException("Can't create stack for unsupported windowingMode="
                    + windowingMode);
        }

        final int stackId = getNextStackId();
        // 走这里
        return createStackUnchecked(windowingMode, activityType, stackId, onTop);
    }

15.4 createStackUnchecked-创建activitystack

    <T extends ActivityStack> T createStackUnchecked(int windowingMode, int activityType,
            int stackId, boolean onTop) {
        if (windowingMode == WINDOWING_MODE_PINNED && activityType != ACTIVITY_TYPE_STANDARD) {
            throw new IllegalArgumentException("Stack with windowing mode cannot with non standard "
                    + "activity type.");
        }
        return (T) new ActivityStack(this, stackId,
                mRootActivityContainer.mStackSupervisor, windowingMode, activityType, onTop);
    }

补充

1. Android中的looper和handler和messagequeue机制

handler,message queue,looper用于线程之间的通信

- message queue:接收message的消息队列
- thread + looper:阻塞式地从消息队列中接收消息并进行处理的线程
- message:可发送的消息的格式
- handler的post和send message:消息发送函数
- handler的handlemessage:消息处理函数

handler通过send message函数传message给message queue;

looper在thread中,looper从message queue中取message,调用handler的handlemessage函数;

handler的handlemessage在looper的线程中处理消息。

2. 设计模式

2.1 工厂模式-提供类的创建接口,不暴露创建逻辑

在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

2.2 建造者(Builder)模式-基本部件不变,组合经常变化

一个 Builder 类会一步一步构造最终的对象。该 Builder 类是独立于其他对象的。

3. activitymanager中的checkslow函数,log打印的形式表示startactivity的过程中哪一步晚了

问题

参考

1. Android中的Thread, Looper和Handler机制(附带HandlerThread与AsyncTask)
https://hit-alibaba.github.io/interview/Android/basic/Android-handler-thread-looper.html
2. 设计模式
https://www.runoob.com/design-pattern/design-pattern-tutorial.html
3. AppWindowToken和WindowToken的添加流程和排序规则
https://blog.csdn.net/qq_34211365/article/details/103913944
posted @ 2021-08-08 14:53  pyjetson  阅读(363)  评论(0编辑  收藏  举报