AMS(二)

startActivity启动流程

第一个阶段
从activity到AMS

Activity.startActivity
  startActivityForResult
    Instrumentation.execStartActivity//返回值去检测是否注册
      ActivityTaskManager.getService().startActivity()//#1 sdk 30 通过获取ActivityTaskManagerService的代理
      ActivityManager.getService().startActivity();//sdk28 通过获取AMS的代理
    //#1
    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }

    private static final Singleton IActivityTaskManagerSingleton =
            new Singleton() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);//通过sm去获取binder
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

第二个阶段
从AMS到ApplicationThread

AMS.startActivity()
  ActivityTaskManagerService.startActivity()//
    startActivityAsUser()//添加一个UserHandle.getCallingUserId()
      startActivityAsUser()//取出tagetUserId
        getActivityStartController().obtainStarter(intent, "startActivityAsUser")//ActivityStartController 在AMS初始化的时候初始化的对象,返回ActivityStarter对象
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setCallingFeatureId(callingFeatureId)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setUserId(userId)
                .execute();//ActivityStarter.execute()
        executeRequest()//这以后是android30的代码,和以前的有出入,这个方法里面会检查Activity权限等。
          startActivityUnchecked()
            startActivityInner()//setInitialState()acitivity的启动模式等,computeLaunchingTaskFlags启动栈
              RootWindowContainer.resumeFocusedStacksTopActivities()
                resumeTopActivityInnerLocked()
                  ActivityStackSupervisor.startSpecificActivity()//#2
                    realStartActivityLocked() //ClientLifecycleManager获取到IApplicationThread的代理
                      ClientLifecycleManager.scheduleTransaction(clientTransaction);
                      //clientTransaction.clientTransaction.addCallback(LaunchActivityItem.obtain())//这里需要记住//#3
                        transaction.schedule();//final IApplicationThread client = transaction.getClient();
                          IApplicationThread.scheduleTransaction()//IApplicationThread是ApplicationThread的代理
                            ApplicationThread.scheduleTransaction()
                              ActivityThread.scheduleTransaction()
                                mH.sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
                                  TransactionExecutor.execute()
                                    executeCallbacks(ClientTransaction transaction) 
                                      item.execute(mTransactionHandler, token, mPendingActions);//#3 item==LaunchActivityItem
                                        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
                                        //client == ClientTransactionHandler -> ActivityThread extends ClientTransactionHandler 
                                          ActivityThread.performLaunchActivity()
                                            mInstrumentation.newActivity()
                                            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
                                                                        
    //#2 ActivityStackSupervisor
    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running? 判断app是否是运行的
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
            knownToBeDead = true;
        }
        
        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        final boolean isTop = andResume && r.isTopRunningActivity();
        //冷启动
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
        // skd 29
        //        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
        //        "activity", r.intent.getComponent(), false, false, true);
    }

冷启动 skd 30

mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,//这个方法重要
                    mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
                    isTop, hostingType, activity.intent.getComponent());
    mH.sendMessage(m);
      ActivityManagerInternal::startProcess//ActivityManagerInternal的是实现类是AMS中的LocalService
        startProcessLocked()
          mProcessList.startProcessLocked()
            startProcess()
              Process.start()
                ZygoteProcess.start()
                  startViaZygote()
                    zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), zygotePolicyFlags,argsForZygote)

      //以下是sendMessage的流程
      AppTimeTracker.deliverResult(mContext);
        PendingIntent.send(context, 0, fillinIntent);
          sendAndReturnResult
            ActivityManager.getService().sendIntentSender()//AMS
              target.sendWithResult();//target == PendingIntentRecord
                sendInner()
                  ActivityTaskManagerInternal.startActivityInPackage()// LocalService extentds ActivityTaskManagerInternal //ActivityTaskManagerService中
                    ActivityStartController.startActivityInPackage()
                       return obtainStarter(intent, reason)
                      .setCallingUid(uid)
                      .setRealCallingPid(realCallingPid)
                      .setRealCallingUid(realCallingUid)
                      .setCallingPackage(callingPackage)
                      .setCallingFeatureId(callingFeatureId)
                      .setResolvedType(resolvedType)
                      .setResultTo(resultTo)
                      .setResultWho(resultWho)
                      .setRequestCode(requestCode)
                      .setStartFlags(startFlags)
                      .setActivityOptions(options)
                      .setUserId(userId)
                      .setInTask(inTask)
                      .setOriginatingPendingIntent(originatingPendingIntent)
                      .setAllowBackgroundActivityStart(allowBackgroundActivityStart)
                      .execute();

冷启动 sdk 29

mService.startProcessLocked(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
  AMS.startProcessLocked()很多次之后
    startProcess()
      Process.start()
        zygoteProcess.start()
          startViaZygote()
            openZygoteSocketIfNeeded//进行socket链接
            zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote)//阻塞//socket通信
            
AMS(二)_第1张图片
startActivity

AMS(二)_第2张图片
AMS和APP持有对方的代理

你可能感兴趣的:(AMS(二))