回忆

按例,咱们对之前的内容进行一个简略的回忆,在Android中,第一个发动的进程是init,它首要解析init.rc文件,发动对应的各式各样的service,例如media,zygote,surfaceflinger,以及敞开了特点服务(类似Windows的注册表)等。接下来咱们讲了Zygote,Zygote是由init发动起来的,它是一个孵化器,孵化了system_server以及其他的使用程序预加载了一些class类和drawable color等资源system_server是体系用来发动办理service进口,比方咱们常用的AMS、WMS、PMS等等都是它来创立的,system_server加载了framework-res.apk,接着调用startBootstrapServicesstartCoreServicesstartOtherServices敞开了非常多的服务,以及敞开了WatchDog监控service。接下来讲了ServiceManage,它是一个服务的提供者,能够让使用获取到体系的各种服务,还有Binder机制。接下来咱们讲了Launcher的发动,它是由system_server敞开的,经过LauncherModel进行IPC通讯(Binder)调用PackageManagerServicequeryIntentActivities获取到一切使用的信息,然后绑定数据源到RecyclerView中,而它的点击事情则是经过ItemClickHandler来进行分发的。

具体的细节能够参阅之前写的文章和视频:

【Android FrameWork】第一个发动的程序–init

【Android FrameWork】Zygote

【Android FrameWork】SystemServer

【Android FrameWork】ServiceManager(一)

【Android FrameWork】ServiceManager(二)

Android Framework】Launcher3

介绍

首要介绍下ActivityManagerService,它是Android体系的中心,它办理了体系的四大组件:ActivityServiceContentProviderBroadcast。它除了办理四大组件外,一起也负责办理和调度一切的进程。

再介绍下咱们这次的第二个主角Activity,它是最复杂的一个组件,它负责UI的显现以及处理各种输入事情(绘制、点击)。关于他的生命周期 借用下官方的图:

【Android Framework】ActivityManagerService(一)

onCreate:当Activity被创立后第一个履行

onStart:当Activity的预备结束后调用

onResume:当Activity成为激活状况时调用

onPause:当Activity被切换到后台的时分,进入暂停状况而且调用

onStop:当Activity不行见的时分调用

onDestory:当Activity被毁掉时调用

正文

上次讲到了Launcher的点击事情,会依据Appinfo 来调用到ActivitystartActivity函数 ,现在咱们就跟一下,看看startActivity是怎样和AMS进行通讯的,以及AMS是怎样处理的呢?

1.AMS的发动

之前在讲system_server的时分,咱们现已知道AMS是运转在system_server中的,代码如下:

文件目录:/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private void startBootstrapServices() {
//……………………
//创立ActivityTaskManagerService  ActivityManagerService 并相关     mSystemServiceManager installer
ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//将服务增加到ServiceManager
mActivityManagerService.setSystemProcess();
//……………………
}
public Lifecycle(Context context) {
    super(context);
    //创立了AMS的实例
    mService = new ActivityManagerService(context, sAtm);
}
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector();
    mContext = systemContext;//设置context 这儿的context 不是咱们使用的context是framework-res.apk
    mFactoryTest = FactoryTest.getMode();
    //获取system_server中的ActivityThread
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();
    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
    //创立处理音讯的线程和Handler
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);
    //创立办理播送的行列 前台和后台
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", foreConstants, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", backConstants, true);
    mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
            "offload", offloadConstants, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    mBroadcastQueues[2] = mOffloadBroadcastQueue;
    //办理service的方针
    mServices = new ActiveServices(this);
    //办理ContentProvider的方针
    mProviderMap = new ProviderMap(this);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    //获取体系目录
    final File systemDir = SystemServiceManager.ensureSystemDir();
    //创立电池状况办理的service
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
            BackgroundThread.get().getHandler());
     //创立进程状况办理的服务
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
    //创立UserController
    mUserController = new UserController(this);
    mPendingIntentController = new PendingIntentController(
            mHandlerThread.getLooper(), mUserController);
    if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
        mUseFifoUiScheduling = true;
    }
    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    //赋值ActivityTaskManagerService
    mActivityTaskManager = atm;
    //进行初始化
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    //创立CPU的统计线程
    mProcessCpuThread = new Thread("CpuTracker") {
        @Override
        public void run() {
            synchronized (mProcessCpuTracker) {
                mProcessCpuInitLatch.countDown();
                mProcessCpuTracker.init();
            }
            while (true) {
                try {
                    try {
                        synchronized(this) {
                            final long now = SystemClock.uptimeMillis();
                            long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                            long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                            //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                            //        + ", write delay=" + nextWriteDelay);
                            if (nextWriteDelay < nextCpuDelay) {
                                nextCpuDelay = nextWriteDelay;
                            }
                            if (nextCpuDelay > 0) {
                                mProcessCpuMutexFree.set(true);
                                this.wait(nextCpuDelay);
                            }
                        }
                    } catch (InterruptedException e) {
                    }
                    updateCpuStatsNow();
                } catch (Exception e) {
                    Slog.e(TAG, "Unexpected exception collecting process stats", e);
                }
            }
        }
    };
    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
    //增加到看门狗 进行检测
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);
    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }
}
private void start() {
    removeAllProcessGroups();
    //敞开cpu线程
    mProcessCpuThread.start();
    //把电池状况办理增加到ServiceManager中
    mBatteryStatsService.publish();
    //把AppOpsService增加到ServiceManager中
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    mActivityTaskManager.onActivityManagerInternalAdded();
    mUgmInternal.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    // Wait for the synchronized block started in mProcessCpuThread,
    // so that any other access to mProcessCpuTracker from main thread
    // will be blocked during mProcessCpuTracker initialization.
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    }
}
public static ActivityManagerService startService(
        SystemServiceManager ssm, ActivityTaskManagerService atm) {
    sAtm = atm;
    //反射创立,并增加到mServices中,调用onStart函数
    return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
private void startOtherServices() {
//……………………
    // 调用 AMS 的 systemReady
    mActivityManagerService.systemReady(...);
}

咱们知道是经过反射构建了ActivityManagerService.Lifecycle方针,初始化了办理四大组件的方针以及一些服务。然后调用setSystemProcess

public void setSystemProcess() {
    try {
    //增加自己到ServiceManager
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
       //增加进程办理服务 能够获取每个进程内存使用情况
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //增加 MemBinder,是用来dump每个进程内存信息的服务
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //增加GraphicsBinder 能够获取每个进程图形加速的服务
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //增加 DbBinder  获取每个进程数据库的服务
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //权限服务
        ServiceManager.addService("permission", new PermissionController(this));
        //进程相关信息
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //获取到当时的ApplicationInfo 也便是framework-res.apk
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
        synchronized (this) {
        //把system_server增加到AMS的process办理者中
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = MY_PID;
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mPidsSelfLocked.put(app);
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }
    //使用发动的监听
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });
}

systemProcess中,又注册了一些服务,获取到了当时的ApplicationInfo方针,然后把ApplicationInfo转换成ProcessRecord方针,增加到AMSmPidsSelfLocked办理中。接着在system_serverstartOtherServices中调用了systemReady

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    synchronized(this) {
        if (mSystemReady) {
        if (goingCallback != null) {
            goingCallback.run();
        }
        return;
    }
        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
                //调用ActivityTaskManagerService的systemReady 预备和task相关的服务
        mActivityTaskManager.onSystemReady();
        //装载用户Profile的信息
        mUserController.onSystemReady();
        //发动App权限监听
        mAppOpsService.systemReady();
        mSystemReady = true;
    }
    //查找需求kill的进程
    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
        for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
            ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            //判别进程是否有FLAG_PERSISTENT标志
            if (!isAllowedWhileBooting(proc.info)){
                if (procsToKill == null) {
                    procsToKill = new ArrayList<ProcessRecord>();
                }
                procsToKill.add(proc);
            }
        }
    }
    synchronized(this) {
        if (procsToKill != null) {//整理
            for (int i=procsToKill.size()-1; i>=0; i--) {
                ProcessRecord proc = procsToKill.get(i);
                mProcessList.removeProcessLocked(proc, true, false, "system update done");
            }
        }
        //整理完成
        mProcessesReady = true;
    }
  //………………
    synchronized (this) {
          //敞开 开机就需求发动的app
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
        //敞开Launcher
        mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
 //发送ACTION_USER_STARTED 播送
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
        | Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
        null, null, 0, null, null, null, OP_NONE,
        null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
        currentUserId);
 //发送ACTION_USER_STARTING播送
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
        null, new IIntentReceiver.Stub() {
            @Override
            public void performReceive(Intent intent, int resultCode, String data,
                    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
                    throws RemoteException {
            }
        }, 0, null, null,
        new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
        null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
        UserHandle.USER_ALL);
        }
    }
}
    final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
            boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride) {
        ProcessRecord app;
        // isolated 为 true 表明要发动一个新的进程
        if (!isolated) {
            // 在现已发动的进程列表中查找
            app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
                    info.uid, true);
        } else {
            app = null;
        }
        if (app == null) {
            // 新建一个 ProcessRecord 方针
            app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
                    new HostingRecord("added application",
                            customProcess != null ? customProcess : info.processName));
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
        }
        // This package really, really can not be stopped.
        try {
            // 将包的stopped状况设置为false
            // 假如为ture那么一切播送都无法接纳,除非带有符号FLAG_INCLUDE_STOPPED_PACKAGES的播送
            // 正经的播送都不会带有这个符号
            AppGlobals.getPackageManager().setPackageStoppedState(
                    info.packageName, false, UserHandle.getUserId(app.uid));
        } catch (RemoteException e) {
        } catch (IllegalArgumentException e) {
            Slog.w(TAG, "Failed trying to unstop package "
                    + info.packageName + ": " + e);
        }
        if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
//            设置persistent符号
            app.setPersistent(true);
            app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
        }
        if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
            mPersistentStartingProcesses.add(app);
            //发动进程
            mProcessList.startProcessLocked(app, new HostingRecord("added application",
                    customProcess != null ? customProcess : app.processName),
                    disableHiddenApiChecks, mountExtStorageFull, abiOverride);
        }
        return app;
    }

systemReady中,调用了ATMS(ActivityTaskManagerService)onSystemReady,以及AppopsServiceUserController进行初始化工作,接着从mPidsSelfLocked集合中查找非FLAG_PERSISTENT标志的进程,而且进行整理。敞开需求开机发动的使用( android:persistent),接着敞开Launcher,发送ACTION_USER_STARTEDACTION_USER_STARTING播送。 /稍后咱们在创立进程的时分会接触到这个集合。这个符号就和PMS相关了,咱们之前没有介绍,简略看一下便是在updatePackagesIfNeeded . getPackagesForDexopt的办法中发送一个ACTION_PRE_BOOT_COMPLETED的播送,假如使用相应这个播送而且参加FLAG_PERSISTENT标志,就能够存活下来。对接纳这个播送的package加载要优先于systemReady,也便是优先其他package的加载。用于开机优先打开的app flag_persistent/

2.进程的发动

1.Launcher 创立恳求的发送

让咱们暂时脱离AMS,回到ActivitystartActivity

public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {//走这儿
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
        //调用Instrumentation的execStartActivity
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        if (requestCode >= 0) {
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
    }
}
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
        //记载从哪里敞开的
    IApplicationThread whoThread = (IApplicationThread) contextThread;
   //target是Launcher自身
    Uri referrer = target != null ? target.onProvideReferrer() : null;
    if (referrer != null) {
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);
    }
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                ActivityResult result = null;
                if (am.ignoreMatchingSpecificIntents()) {
                    result = am.onStartActivity(intent);
                }
                if (result != null) {
                    am.mHits++;
                    return result;
                } else if (am.match(who, null, intent)) {
                    am.mHits++;
                    if (am.isBlocking()) {
                        return requestCode >= 0 ? am.getResult() : null;
                    }
                    break;
                }
            }
        }
    }
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        //在这儿进行跨进程通讯 调用ATMS的startActivity 留意这儿是两次IPC通讯 首要获取ATMS(BinderProxy) 然后调用ATMS的startActivity
        int result = ActivityTaskManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

终究调用到/frameworks/base/core/java/android/app/Instrumentation.javaexecStartActivity函数。在这儿进行了两次IPC通讯(首要获取ATMS,再经过BinderProxy调用startActivity)。 文件目录:/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java 到了ATMSstartActivity

public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}
public 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*/);
}
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");
    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();
}
int execute() {
        if (mRequest.mayWait) {//这儿是true
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                    mRequest.intent, mRequest.resolvedType,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                    mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup,
                    mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
        } 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);
        }
}
//调用到mayWait
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) {
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunching(intent);
    //依据intent获取到需求发动的Activity信息
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    synchronized (mService.mGlobalLock) {
        //创立ActivityRecord
        final ActivityRecord[] outRecord = new ActivityRecord[1];
        //调用startActivity
        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)
        return res;
    }
}
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) {
    mLastStartReason = reason;
    mLastStartActivityTimeMs = System.currentTimeMillis();
    mLastStartActivityRecord[0] = null;
    //调用startActivity
    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) {
        outActivity[0] = mLastStartActivityRecord[0];
    }
    return getExternalResult(mLastStartActivityResult);
}
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) {
    int err = ActivityManager.START_SUCCESS;
    if (caller != null) {
    //获取到caller的进程信息 Launcher
        callerApp = mService.getProcessController(caller);
        if (callerApp != null) {
            callingPid = callerApp.getPid();
            callingUid = callerApp.mInfo.uid;
        } else {
            Slog.w(TAG, "Unable to find app for caller " + caller
                    + " (pid=" + callingPid + ") when starting: "
                    + intent.toString());
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }
    //查看调用者的相关权限
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
            requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
            inTask != null, callerApp, resultRecord, resultStack);
            //防火墙是否屏蔽了intent
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
    abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
            callingPackage);
    boolean restrictedBgActivity = false;
    ActivityOptions checkedOptions = options != null
            ? options.getOptions(intent, aInfo, callerApp, mSupervisor) : null;
    if (allowPendingRemoteAnimationRegistryLookup) {
        checkedOptions = mService.getActivityStartController()
                .getPendingRemoteAnimationRegistry()
                .overrideOptionsIfNeeded(callingPackage, checkedOptions);
    }
    if (mService.mController != null) {
        try {
        //monkey相关的 回来是否需求拦截Activity的发动 return true
            Intent watchIntent = intent.cloneFilter();
            abort |= !mService.mController.activityStarting(watchIntent,
                    aInfo.applicationInfo.packageName);
        } catch (RemoteException e) {
            mService.mController = null;
        }
    }
    if (abort) {//需求拦截 直接退出
        return START_ABORTED;
    }
   //审阅完成之后 开端发动
    //创立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[0] = r;
    }
    if (r.appTimeTracker == null && sourceRecord != null) {
        r.appTimeTracker = sourceRecord.appTimeTracker;
    }
    //获取到当时的ActivityStack
    final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
    //查看是否能够进行切换
    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))) {
            //假如不能切换进程 把Activity存入mPendingActivityLaunches中去
                mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
                        sourceRecord, startFlags, stack, callerApp));
            }
            ActivityOptions.abort(checkedOptions);
            return ActivityManager.START_SWITCHES_CANCELED;
        }
    }
    mService.onStartActivitySetDidAppSwitch();
    mController.doPendingActivityLaunches(false);
    //调用startActivity
    final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
            true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
    return res;
}
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;
        mService.mWindowManager.deferSurfaceLayout();
        //调用startActivityUnchecked
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
    return result;
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity, boolean restrictedBgActivity) {
    //判别Activity 是否需求插入新的task
    //1.设置了new_task标签
    //2.发动形式是singleTask
    //3.发动形式是singleInstance
    ActivityRecord reusedActivity = getReusableIntentActivity();
  //假如正在发动的活动与当时在顶部的活动相同,那么咱们需求查看它是否应该只发动一次。
    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))
            && (!top.isActivityTypeHome() || top.getDisplayId() == mPreferredDisplayId);
    if (dontStart) { //不需求发动
        topStack.mLastPausedActivity = null;
        if (mDoResume) {
            mRootActivityContainer.resumeFocusedStacksTopActivities();
        }
        ActivityOptions.abort(mOptions);
        if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
            return START_RETURN_INTENT_TO_CALLER;
        }
        //履行newIntent
        deliverNewIntent(top);
        mSupervisor.handleNonResizableTaskIfNeeded(top.getTaskRecord(), preferredWindowingMode,
                mPreferredDisplayId, topStack);
        return START_DELIVERED_TO_TOP;
    }
    boolean newTask = false;
    final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
            ? mSourceRecord.getTaskRecord() : null;
    int result = START_SUCCESS;
    //判别是否需求一个新的task
    if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
            && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
        newTask = true;
        result = setTaskFromReuseOrCreateNewTask(taskToAffiliate);
    } else if (mSourceRecord != null) {
        result = setTaskFromSourceRecord();
    } else if (mInTask != null) {
        result = setTaskFromInTask();
    } else {
        result = setTaskToCurrentTopOrCreateNewTask();
    }
    if (result != START_SUCCESS) {
        return result;
    }
    //敞开activity 首要是把ActivityReecord方针参加task的顶部,把task参加到mTaskHistory顶部
    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
            mOptions);
    if (mDoResume) {
        final ActivityRecord topTaskActivity =
                mStartActivity.getTaskRecord().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {//没有焦点,无法resume 履行动画
            mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
            //履行动画
            mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
        } else {//不行见
            if (mTargetStack.isFocusable()
                    && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            mRootActivityContainer.resumeFocusedStacksTopActivities(
                    mTargetStack, mStartActivity, mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTaskRecord());
    }
    return START_SUCCESS;
}
void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
        boolean newTask, boolean keepCurTransition, ActivityOptions options) {
    if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
        insertTaskAtTop(rTask, r);
    }
}
//调用resumeFocusedStacksTopActivities
boolean resumeFocusedStacksTopActivities(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (!mStackSupervisor.readyToResume()) {
        return false;
    }
    boolean result = false;
    //判别方针ActivityStack是否处于焦点,是的话调用resumeTopActivityUnckedLocked进行进一步发动流程
    if (targetStack != null && (targetStack.isTopStackOnDisplay()
            || getTopDisplayFocusedStack() == targetStack)) {
        result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    //遍历一切显现的activityDisplays
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        boolean resumedOnDisplay = false;
        final ActivityDisplay display = mActivityDisplays.get(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            //获取到activityStack
            final ActivityStack stack = display.getChildAt(stackNdx);
            //获取到topActivity
            final ActivityRecord topRunningActivity = stack.topRunningActivityLocked();
            if (!stack.isFocusableAndVisible() || topRunningActivity == null) {
                continue;
            }
            if (stack == targetStack) {
                resumedOnDisplay |= result;
                continue;
            }
            if (display.isTopStack(stack) && topRunningActivity.isState(RESUMED)) {
                stack.executeAppTransition(targetOptions);//履行动画
            } else {
                resumedOnDisplay |= topRunningActivity.makeActiveIfNeeded(target);
            }
        }
        if (!resumedOnDisplay) {//没有被激活
            final ActivityStack focusedStack = display.getFocusedStack();
            if (focusedStack != null) {
                focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
        }
    }
    return result;
}
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
//mInResumeTopActivity 表明当时处于resumeTopActivity过程中,防止重复递归调用
    if (mInResumeTopActivity) {
        return false;
    }
    boolean result = false;
    try {
        mInResumeTopActivity = true;
        //在这儿真实敞开Activity
        result = resumeTopActivityInnerLocked(prev, options);
        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mInResumeTopActivity = false;
    }
    return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.isBooting() && !mService.isBooted()) {//AMS还没敞开成功
        return false;
    }
    //获取到将要显现的Activity
    ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
    final boolean hasRunningActivity = next != null;
    //判别是否没有Attached
    if (hasRunningActivity && !isAttached()) {
        return false;
    }
//整理AppWindowToekn
    mRootActivityContainer.cancelInitializingActivities();
    //符号是否调用Activity的performUserLeaving回调 要脱离的回调
    boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;
    if (!hasRunningActivity) {
        return resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
    }
    //是否延迟显现
    next.delayedResume = false;
    final ActivityDisplay display = getDisplay();
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    //判别是否有没暂停的activity
    if (!mRootActivityContainer.allPausedActivitiesComplete()) {
        return false;
    }
    //用于使用耗电统计 wake lock相关的WorkSource
    mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
    //pause 非当时焦点的ActivityStack中的Activity。
    boolean pausing = getDisplay().pauseBackStacks(userLeaving, next, false);
    //mResumedActivity 表明的是当时正在显现的Activity 也便是Launcher
    if (mResumedActivity != null) {
    //pause launcher
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
     // 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;
}

经过PMS查询到需求敞开的activity 以及使用信息,终究会调到ActivityStarterstartActivity,判别各种flag,权限,把需求敞开的Activity调整到task顶部,把task调整到HistoryTasks的顶部。暂停当时的显现界面,再判别假如需求发动的Activity现已显现了,直接调用resume的流程,否则调用startSpecificActivityLocked进入敞开流程。

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    final WindowProcessController wpc =
            mService.getProcessController(r.processName, r.info.applicationInfo.uid);
    boolean knownToBeDead = false;
    if (wpc != null && wpc.hasThread()) {//使用进程现已存在
        try {
        //直接敞开Activity
            realStartActivityLocked(r, wpc, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
        knownToBeDead = true;
    }
    if (getKeyguardController().isKeyguardLocked()) {
        r.notifyUnknownVisibilityLaunched();
    }
        //发动进程
        final Message msg = PooledLambda.obtainMessage(
                ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
        mService.mH.sendMessage(msg);
}

咱们从Launcher点击过来是没有敞开进程的,所以咱们需求先敞开进程。终于到了进程的发动了,上面的逻辑代码判别比较多,感兴趣的,能够自己去跟踪下,我就先介绍发动流程了。走到了startProcess

//这儿的processName便是包名 applicationInfo便是Application
public void startProcess(String processName, ApplicationInfo info,
        boolean knownToBeDead, String hostingType, ComponentName hostingName) {
        synchronized (ActivityManagerService.this) {
            startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                    new HostingRecord(hostingType, hostingName),
                    false /* allowWhileBooting */, false /* isolated */,
                    true /* keepIfLarge */);
      }
}
//isolated = false 表明没发动过
final ProcessRecord startProcessLocked(String processName,
        ApplicationInfo info, boolean knownToBeDead, int intentFlags,
        HostingRecord hostingRecord, boolean allowWhileBooting,
        boolean isolated, boolean keepIfLarge) {
    return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
            hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
            null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
            null /* crashHandler */);
}
文件目录:/frameworks/base/services/core/java/com/android/server/am/ProcessList.java
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
        boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
        String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    if (app == null) {
       //创立ProcessRecord 方针
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid, hostingRecord);
        if (app == null) {
            return null;
        }
        app.crashHandler = crashHandler;
        app.isolatedEntryPoint = entryPoint;
        app.isolatedEntryPointArgs = entryPointArgs;
        checkSlow(startTime, "startProcess: done creating new process record");
    }
    //调用 startProcessLocked敞开进程
    final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
    return success ? app : null;
}
boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
        boolean disableHiddenApiChecks, boolean mountExtStorageFull,
        String abiOverride) {
    if (app.pendingStart) {
        return true;
    }
    long startTime = SystemClock.elapsedRealtime();
    if (app.pid > 0 && app.pid != ActivityManagerService.MY_PID) {
    //从集合中移除进程的id,防止重复创立
        mService.mPidsSelfLocked.remove(app);
        //移除音讯行列的PROC_START_TIMEOUT_MSG音讯
        mService.mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
        app.setPid(0);
        app.startSeq = 0;
    }
    mService.mProcessesOnHold.remove(app);
        //设置entryPoint 为"android.app.ActivityThread"
    final String entryPoint = "android.app.ActivityThread";
    //调用startProcessLocked
    return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
                runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, 
}
boolean startProcessLocked(HostingRecord hostingRecord,
        String entryPoint,
        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
        long startTime) {
    app.pendingStart = true;
    app.killedByAm = false;
    app.removed = false;
    app.killed = false;
    final long startSeq = app.startSeq = ++mProcStartSeqCounter;
    app.setStartParams(uid, hostingRecord, seInfo, startTime);
    app.setUsingWrapper(invokeWith != null
            || SystemProperties.get("wrap." + app.processName) != null);
    mPendingStarts.put(startSeq, app);
    if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {//异步发动
        if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,
                "Posting procStart msg for " + app.toShortString());
        mService.mProcStartHandler.post(() -> {
            try {
                final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
                        entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
                        app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
                synchronized (mService) {
                //发送一个延时音讯 用来监听使用发动
                    handleProcessStartedLocked(app, startResult, startSeq);
                }
            } catch (RuntimeException e) {
                synchronized (mService) {
                    Slog.e(ActivityManagerService.TAG, "Failure starting process "
                            + app.processName, e);
                    mPendingStarts.remove(startSeq);
                    app.pendingStart = false;
                    mService.forceStopPackageLocked(app.info.packageName,
                            UserHandle.getAppId(app.uid),
                            false, false, true, false, false, app.userId, "start failure");
                }
            }
        });
        return true;
    } else {
        try {
        //发动使用
            final Process.ProcessStartResult startResult = startProcess(hostingRecord,
                    entryPoint, app,
                    uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                    invokeWith, startTime);
                    //发送一个延时音讯,来监听使用发动
            handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
                    startSeq, false);
        } catch (RuntimeException e) {
            Slog.e(ActivityManagerService.TAG, "Failure starting process "
                    + app.processName, e);
            app.pendingStart = false;
            mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
                    false, false, true, false, false, app.userId, "start failure");
        }
        return app.pid > 0;
    }
}
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
        long startTime) {
        final Process.ProcessStartResult startResult;
          //咱们是到这儿来 创立AppZygote 调用start函数来敞开
        final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
        startResult = appZygote.getProcess().start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, null, app.info.packageName,
                    /*useUsapPool=*/ false,
                    new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        return startResult;
}
//看看怎么创立AppZygote的
private AppZygote createAppZygoteForProcessIfNeeded(final ProcessRecord app) {
    synchronized (mService) {
    //获取到uid
        final int uid = app.hostingRecord.getDefiningUid();
        //这儿是拿不到的 默许是没有的
        AppZygote appZygote = mAppZygotes.get(app.info.processName, uid);
        final ArrayList<ProcessRecord> zygoteProcessList;
        if (appZygote == null) {
            final IsolatedUidRange uidRange =
                    mAppIsolatedUidRangeAllocator.getIsolatedUidRangeLocked(
                            app.info.processName, app.hostingRecord.getDefiningUid());
            final int userId = UserHandle.getUserId(uid);
            final int firstUid = UserHandle.getUid(userId, uidRange.mFirstUid);
            final int lastUid = UserHandle.getUid(userId, uidRange.mLastUid);
            ApplicationInfo appInfo = new ApplicationInfo(app.info);
            appInfo.packageName = app.hostingRecord.getDefiningPackageName();
            appInfo.uid = uid;
            //创立AppZygote 存入mAppZygotes中
            appZygote = new AppZygote(appInfo, uid, firstUid, lastUid);
            mAppZygotes.put(app.info.processName, uid, appZygote);
            zygoteProcessList = new ArrayList<ProcessRecord>();
            mAppZygoteProcesses.put(appZygote, zygoteProcessList);
        } else {
            mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG, appZygote);
            zygoteProcessList = mAppZygoteProcesses.get(appZygote);
        }
        zygoteProcessList.add(app);
        return appZygote;
    }
}
//看看他的start函数
public final Process.ProcessStartResult start(@NonNull final String processClass,
                                              final String niceName,
                                              int uid, int gid, @Nullable int[] gids,
                                              int runtimeFlags, int mountExternal,
                                              int targetSdkVersion,
                                              @Nullable String seInfo,
                                              @NonNull String abi,
                                              @Nullable String instructionSet,
                                              @Nullable String appDataDir,
                                              @Nullable String invokeWith,
                                              @Nullable String packageName,
                                              boolean useUsapPool,
                                              @Nullable String[] zygoteArgs) {
    if (fetchUsapPoolEnabledPropWithMinInterval()) {
        informZygotesOfUsapPoolStatus();
    }
    try {
    //调用startViaZygote
        return startViaZygote(processClass, niceName, uid, gid, gids,
                runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
                packageName, useUsapPool, zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        Log.e(LOG_TAG,
                "Starting VM process through Zygote failed");
        throw new RuntimeException(
                "Starting VM process through Zygote failed", ex);
    }
}
//到了敞开进程的地方了 processClass便是咱们传入的ActivityThread
private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
                                                  @Nullable final String niceName,
                                                  final int uid, final int gid,
                                                  @Nullable final int[] gids,
                                                  int runtimeFlags, int mountExternal,
                                                  int targetSdkVersion,
                                                  @Nullable String seInfo,
                                                  @NonNull String abi,
                                                  @Nullable String instructionSet,
                                                  @Nullable String appDataDir,
                                                  @Nullable String invokeWith,
                                                  boolean startChildZygote,
                                                  @Nullable String packageName,
                                                  boolean useUsapPool,
                                                  @Nullable String[] extraArgs)
                                                  throws ZygoteStartFailedEx {
    ArrayList<String> argsForZygote = new ArrayList<>();
    argsForZygote.add("--runtime-args");
    argsForZygote.add("--setuid=" + uid);
    argsForZygote.add("--setgid=" + gid);
    argsForZygote.add("--runtime-flags=" + runtimeFlags);
    if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
        argsForZygote.add("--mount-external-default");
    } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
        argsForZygote.add("--mount-external-read");
    } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
        argsForZygote.add("--mount-external-write");
    } else if (mountExternal == Zygote.MOUNT_EXTERNAL_FULL) {
        argsForZygote.add("--mount-external-full");
    } else if (mountExternal == Zygote.MOUNT_EXTERNAL_INSTALLER) {
        argsForZygote.add("--mount-external-installer");
    } else if (mountExternal == Zygote.MOUNT_EXTERNAL_LEGACY) {
        argsForZygote.add("--mount-external-legacy");
    }
    argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
    if (gids != null && gids.length > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("--setgroups=");
        int sz = gids.length;
        for (int i = 0; i < sz; i++) {
            if (i != 0) {
                sb.append(',');
            }
            sb.append(gids[i]);
        }
        argsForZygote.add(sb.toString());
    }
    if (niceName != null) {
        argsForZygote.add("--nice-name=" + niceName);
    }
    if (seInfo != null) {
        argsForZygote.add("--seinfo=" + seInfo);
    }
    if (instructionSet != null) {
        argsForZygote.add("--instruction-set=" + instructionSet);
    }
    if (appDataDir != null) {
        argsForZygote.add("--app-data-dir=" + appDataDir);
    }
    if (invokeWith != null) {
        argsForZygote.add("--invoke-with");
        argsForZygote.add(invokeWith);
    }
    if (startChildZygote) {
        argsForZygote.add("--start-child-zygote");
    }
    if (packageName != null) {
        argsForZygote.add("--package-name=" + packageName);
    }
    argsForZygote.add(processClass);
    if (extraArgs != null) {
        Collections.addAll(argsForZygote, extraArgs);
    }
    synchronized(mLock) {
        //开端和Zygote通讯
        return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                          useUsapPool,
                                          argsForZygote);
    }
}
//打开Zygote的socket
private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
    try {
        attemptConnectionToPrimaryZygote();
        if (primaryZygoteState.matches(abi)) {
            return primaryZygoteState;
        }
        if (mZygoteSecondarySocketAddress != null) {
            // The primary zygote didn't match. Try the secondary.
            attemptConnectionToSecondaryZygote();
            if (secondaryZygoteState.matches(abi)) {
                return secondaryZygoteState;
            }
        }
    } catch (IOException ioe) {
        throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
    }
    throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}
private void attemptConnectionToPrimaryZygote() throws IOException {
    if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
    //进行zygote衔接 address = zygote 创立zygote的时分命名便是zygote 包装成ZygoteState
        primaryZygoteState =
                ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
        maybeSetApiBlacklistExemptions(primaryZygoteState, false);
        maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
        maybeSetHiddenApiAccessStatslogSampleRate(primaryZygoteState);
    }
}
//预备参数
private Process.ProcessStartResult zygoteSendArgsAndGetResult(
        ZygoteState zygoteState, boolean useUsapPool, @NonNull ArrayList<String> args)
        throws ZygoteStartFailedEx {
    String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";
    if (useUsapPool && mUsapPoolEnabled && canAttemptUsap(args)) {//这儿是false
        try {
            return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
        } catch (IOException ex) {
            // If there was an IOException using the USAP pool we will log the error and
            // attempt to start the process through the Zygote.
            Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "
                    + ex.getMessage());
        }
    }
    return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
}
private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
        ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
        final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
        final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
        //参数写入
        zygoteWriter.write(msgStr);
        zygoteWriter.flush();
         //创立result方针
        Process.ProcessStartResult result = new Process.ProcessStartResult();
        result.pid = zygoteInputStream.readInt();//获取回来的pid
        result.usingWrapper = zygoteInputStream.readBoolean();
        return result;
}

AMSATMS的预备工作还是蛮多的,这儿首要也贴出了Activity的预备工作,可是我没还没有敞开进程,所以咱们先看敞开进程的,调用到Process的start函数,终究调用到attemptZygoteSendArgsAndGetResult,给Zygote发送数据。

2.Zygote接纳到数据之后的处理

让咱们回到Zygote中,文件为ZygoteServer.javarunSelectLoop中。

Runnable runSelectLoop(String abiList) {
    ArrayList<FileDescriptor> socketFDs = new ArrayList<FileDescriptor>();
    ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
    socketFDs.add(mZygoteSocket.getFileDescriptor());
    peers.add(null);
    while (true) {
        fetchUsapPoolPolicyPropsWithMinInterval();
        int[] usapPipeFDs = null;
        StructPollfd[] pollFDs = null;//需求监听的fds
        if (mUsapPoolEnabled) {
            usapPipeFDs = Zygote.getUsapPipeFDs();
            pollFDs = new StructPollfd[socketFDs.size() + 1 + usapPipeFDs.length];
        } else {
            pollFDs = new StructPollfd[socketFDs.size()];
        }
        int pollIndex = 0;
        for (FileDescriptor socketFD : socketFDs) {
            pollFDs[pollIndex] = new StructPollfd();
            pollFDs[pollIndex].fd = socketFD;
            pollFDs[pollIndex].events = (short) POLLIN;//对每一个socket需求重视POLLIN
            ++pollIndex;
        }
        final int usapPoolEventFDIndex = pollIndex;
        if (mUsapPoolEnabled) {
            pollFDs[pollIndex] = new StructPollfd();
            pollFDs[pollIndex].fd = mUsapPoolEventFD;
            pollFDs[pollIndex].events = (short) POLLIN;
            ++pollIndex;
            for (int usapPipeFD : usapPipeFDs) {
                FileDescriptor managedFd = new FileDescriptor();
                managedFd.setInt$(usapPipeFD);
                pollFDs[pollIndex] = new StructPollfd();
                pollFDs[pollIndex].fd = managedFd;
                pollFDs[pollIndex].events = (short) POLLIN;
                ++pollIndex;
            }
        }
        try {//zygote堵塞在这儿等候poll事情
            Os.poll(pollFDs, -1);
        } catch (ErrnoException ex) {
            throw new RuntimeException("poll failed", ex);
        }
        boolean usapPoolFDRead = false;
        //留意这儿是选用的倒序方式的,也便是说优先处理现已树立衔接的恳求,后处理新树立链接的恳求
        while (--pollIndex >= 0) {
            if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
                continue;
            }
            if (pollIndex == 0) {//初始化的时分socketFDs中只有server socket。所以会创立新的通讯衔接调用acceptCommandPeer
                // Zygote server socket
                ZygoteConnection newPeer = acceptCommandPeer(abiList);
                peers.add(newPeer);
                socketFDs.add(newPeer.getFileDescriptor());
            } else if (pollIndex < usapPoolEventFDIndex) {
                // Session socket accepted from the Zygote server socket
                try {//获取到客户端链接
                    ZygoteConnection connection = peers.get(pollIndex);
                    //客户端有恳求进行处理
                    final Runnable command = connection.processOneCommand(this);
                    if (mIsForkChild) {
                        if (command == null) {
                            throw new IllegalStateException("command == null");
                        }
                        return command;
                    } else {
                        if (command != null) {
                            throw new IllegalStateException("command != null");
                        }
                        // We don't know whether the remote side of the socket was closed or
                        // not until we attempt to read from it from processOneCommand. This
                        // shows up as a regular POLLIN event in our regular processing loop.
                        if (connection.isClosedByPeer()) {
                            connection.closeSocket();
                            peers.remove(pollIndex);
                            socketFDs.remove(pollIndex);
                        }
                    }
                } catch (Exception e) {
                    if (!mIsForkChild) {
                        Slog.e(TAG, "Exception executing zygote command: ", e);
                        ZygoteConnection conn = peers.remove(pollIndex);
                        conn.closeSocket();
                        socketFDs.remove(pollIndex);
                    } else {
                        Log.e(TAG, "Caught post-fork exception in child process.", e);
                        throw e;
                    }
                } finally {
                    mIsForkChild = false;
                }
            } else {
                long messagePayload = -1;
                try {
                    byte[] buffer = new byte[Zygote.USAP_MANAGEMENT_MESSAGE_BYTES];
                    int readBytes = Os.read(pollFDs[pollIndex].fd, buffer, 0, buffer.length);
                    if (readBytes == Zygote.USAP_MANAGEMENT_MESSAGE_BYTES) {
                        DataInputStream inputStream =
                                new DataInputStream(new ByteArrayInputStream(buffer));
                        messagePayload = inputStream.readLong();
                    } else {
                        Log.e(TAG, "Incomplete read from USAP management FD of size "
                                + readBytes);
                        continue;
                    }
                } catch (Exception ex) {
                    if (pollIndex == usapPoolEventFDIndex) {
                        Log.e(TAG, "Failed to read from USAP pool event FD: "
                                + ex.getMessage());
                    } else {
                        Log.e(TAG, "Failed to read from USAP reporting pipe: "
                                + ex.getMessage());
                    }
                    continue;
                }
                if (pollIndex > usapPoolEventFDIndex) {
                    Zygote.removeUsapTableEntry((int) messagePayload);
                }
                usapPoolFDRead = true;
            }
        }
        if (usapPoolFDRead) {
            int[] sessionSocketRawFDs =
                    socketFDs.subList(1, socketFDs.size())
                            .stream()
                            .mapToInt(fd -> fd.getInt$())
                            .toArray();
            final Runnable command = fillUsapPool(sessionSocketRawFDs);
            if (command != null) {
                return command;
            }
        }
    }
}

进入processOneCommand处理客户端的恳求.

Runnable processOneCommand(ZygoteServer zygoteServer) {
        String args[];
        ZygoteArguments parsedArgs = null;
        FileDescriptor[] descriptors;
            args = Zygote.readArgumentList(mSocketReader);
            descriptors = mSocket.getAncillaryFileDescriptors();
        if (args == null) {
            isEof = true;
            return null;
        }
        int pid = -1;
        FileDescriptor childPipeFd = null;
        FileDescriptor serverPipeFd = null;
        //解析传递过来的参数
        parsedArgs = new ZygoteArguments(args);
        //调用native的fork
        pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
                parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
                parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
                parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
        try {
            if (pid == 0) {
                // 在子进程中 首要关闭掉ServerSocket,由于它是Zygote孵化出来的 所以socket 需求关闭掉。
                zygoteServer.setForkChild();
                zygoteServer.closeServerSocket();
                IoUtils.closeQuietly(serverPipeFd);
                serverPipeFd = null;
                //调用HandleChildProc mStartChildZygote = --start-child-zygote
                return handleChildProc(parsedArgs, descriptors, childPipeFd,
                        parsedArgs.mStartChildZygote);
            } else {
                // In the parent. A pid < 0 indicates a failure and will be handled in
                // handleParentProc.
                IoUtils.closeQuietly(childPipeFd);
                childPipeFd = null;
                handleParentProc(pid, descriptors, serverPipeFd);
                return null;
            }
        } finally {
            IoUtils.closeQuietly(childPipeFd);
            IoUtils.closeQuietly(serverPipeFd);
        }
    }
static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
        JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
        jint runtime_flags, jobjectArray rlimits,
        jint mount_external, jstring se_info, jstring nice_name,
        jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
        jstring instruction_set, jstring app_data_dir) {
    ……………………
    pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
    if (pid == 0) {
      SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
                       capabilities, capabilities,
                       mount_external, se_info, nice_name, false,
                       is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
    }
    return pid;
}
到native层fork进程
static jint com_android_internal_os_Zygote_nativeForkAndSpecialize(
        JNIEnv* env, jclass, jint uid, jint gid, jintArray gids,
        jint runtime_flags, jobjectArray rlimits,
        jint mount_external, jstring se_info, jstring nice_name,
        jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote,
        jstring instruction_set, jstring app_data_dir) {
    ……………………
    pid_t pid = ForkCommon(env, false, fds_to_close, fds_to_ignore);
    if (pid == 0) {
      SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
                       capabilities, capabilities,
                       mount_external, se_info, nice_name, false,
                       is_child_zygote == JNI_TRUE, instruction_set, app_data_dir);
    }
    return pid;
}
static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
                        const std::vector<int>& fds_to_close,
                        const std::vector<int>& fds_to_ignore) {
  SetSignalHandlers();
  ……………………
  pid_t pid = fork();//fork出来客户端恳求的进程。
  if (pid == 0) {
    PreApplicationInit();
    DetachDescriptors(env, fds_to_close, fail_fn);
    ClearUsapTable();
    gOpenFdTable->ReopenOrDetach(fail_fn);
    android_fdsan_set_error_level(fdsan_error_level);
  } else {
    ALOGD("Forked child process %d", pid);
  }
后边流程同Zygote我就省掉了 能够参阅我之前写的Zygote 

Zygotefork出了子进程,然后调用了onZygoteInit初始化了ProcessState打开了binder等等。这儿传入的processClass 是ActivityThread,所以会进入到ActivityThreadmain函数。这儿的ActivityThread便是咱们使用进程的了。

3.使用进程的初始化

文件目录:/frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
    AndroidOs.install();
    CloseGuard.setEnabled(false);
    Environment.initForCurrentUser();
    TrustedCertificateStore.setDefaultUserDirectory(configDir);
    Process.setArgV0("<pre-initialized>");
    //预备MainLooper
    Looper.prepareMainLooper();
    long startSeq = 0;
    if (args != null) {
        for (int i = args.length - 1; i >= 0; --i) {
            if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                startSeq = Long.parseLong(
                        args[i].substring(PROC_START_SEQ_IDENT.length()));
            }
        }
    }
    //创立ActivityThread 之前system_server是经过静态函数systemMain来创立的 现在直接new的,设置了mResourcesManager
    ActivityThread thread = new ActivityThread();
    //调用了attach
    thread.attach(false, startSeq);
    if (sMainThreadHandler == null) {
        sMainThreadHandler = thread.getHandler();
    }
    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    Looper.loop();//敞开loop
}
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {//之前system_server 不走这儿,现在咱们走这儿了
    //设置AppName
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        final IActivityManager mgr = ActivityManager.getService();
        try {
        //调用AMS的attachApplication 这儿又是一次IPC通讯 由于咱们当时是使用进程了
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    ViewRootImpl.addConfigCallback(configChangedCallback);
}
AMS的attachApplication
public final void attachApplication(IApplicationThread thread, long startSeq) {
    if (thread == null) {
        throw new SecurityException("Invalid application interface");
    }
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        //调用attachApplicationLocked
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
        int pid, int callingUid, long startSeq) {
    //依据pid获取到app信息
    app = mPidsSelfLocked.get(pid);
    //thread指的是ActivityThread 所以这儿是IPC通讯
    thread.bindApplication(processName, appInfo, providers,
        instr2.mClass,
        profilerInfo, instr2.mArguments,
        instr2.mWatcher,
        instr2.mUiAutomationConnection, testMode,
        mBinderTransactionTrackingEnabled, enableTrackAllocation,
        isRestrictedBackupMode || !normalMode, app.isPersistent(),
        new Configuration(app.getWindowProcessController().getConfiguration()),
        app.compat, getCommonServicesLocked(app.isolated),
        mCoreSettingsObserver.getCoreSettingsLocked(),
        buildSerial, autofillOptions, contentCaptureOptions);
//从starting applications中移除
mPersistentStartingProcesses.remove(app);
    if (normalMode) {
        try {
        //发动activity
            didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
            badApp = true;
        }
    }
    if (!badApp) {
        try {
            didSomething |= mServices.attachApplicationLocked(app, processName);
            checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
        } catch (Exception e) {
            Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
            badApp = true;
        }
    }
    return true;
}
//到了ActivityThread的bindApplication
public final void bindApplication(String processName, ApplicationInfo appInfo,
        List<ProviderInfo> providers, ComponentName instrumentationName,
        ProfilerInfo profilerInfo, Bundle instrumentationArgs,
        IInstrumentationWatcher instrumentationWatcher,
        IUiAutomationConnection instrumentationUiConnection, int debugMode,
        boolean enableBinderTracking, boolean trackAllocation,
        boolean isRestrictedBackupMode, boolean persistent, Configuration config,
        CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
        String buildSerial, AutofillOptions autofillOptions,
        ContentCaptureOptions contentCaptureOptions) {
    setCoreSettings(coreSettings);
    AppBindData data = new AppBindData();
    data.processName = processName;
    data.appInfo = appInfo;
    data.providers = providers;
    data.instrumentationName = instrumentationName;
    data.instrumentationArgs = instrumentationArgs;
    data.instrumentationWatcher = instrumentationWatcher;
    data.instrumentationUiAutomationConnection = instrumentationUiConnection;
    data.debugMode = debugMode;
    data.enableBinderTracking = enableBinderTracking;
    data.trackAllocation = trackAllocation;
    data.restrictedBackupMode = isRestrictedBackupMode;
    data.persistent = persistent;
    data.config = config;
    data.compatInfo = compatInfo;
    data.initProfilerInfo = profilerInfo;
    data.buildSerial = buildSerial;
    data.autofillOptions = autofillOptions;
    data.contentCaptureOptions = contentCaptureOptions;
    //给handle 发送BIND_APPLICATION data便是上边的data
    sendMessage(H.BIND_APPLICATION, data);
}
在handleMessage中
case BIND_APPLICATION:
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
    AppBindData data = (AppBindData)msg.obj;
    //调用handleBindApplication
    handleBindApplication(data);
    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    break;
private void handleBindApplication(AppBindData data) {
    //把UI线程注册成运转时 敏感线程
    VMRuntime.registerSensitiveThread();
    //记载进程运转时刻
    Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
    //设置进程名
    android.ddm.DdmHandleAppName.setAppName(data.processName,
                                            UserHandle.myUserId());
    VMRuntime.setProcessPackageName(data.appInfo.packageName);
    //使用目录
    VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
    if (mProfiler.profileFd != null) {
        mProfiler.startProfiling();
    }
//获取到loadedApk 并存入到mPackages中
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
//创立Instrumentation
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
    //创立Application
    Application app;
    //创立使用
        app = data.info.makeApplication(data.restrictedBackupMode, null);
        mInitialApplication = app;
        mInstrumentation.onCreate(data.instrumentationArgs);
        mInstrumentation.callApplicationOnCreate(app);
    }
}
//创立Application
public Application makeApplication(boolean forceDefaultAppClass,
        Instrumentation instrumentation) {
    if (mApplication != null) {//假如现已创立过了 回来
        return mApplication;
    }
    Application app = null;
    //拿到applicationName 便是咱们配置的Application 默许是android.app.Application
    String appClass = mApplicationInfo.className; 
    if (forceDefaultAppClass || (appClass == null)) {
        appClass = "android.app.Application";
    }
        java.lang.ClassLoader cl = getClassLoader();
        //创立上下文
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        //创立Application
        app = mActivityThread.mInstrumentation.newApplication(
                cl, appClass, appContext);
        appContext.setOuterContext(app);
   //增加到mAllApplications中
    mActivityThread.mAllApplications.add(app);
    mApplication = app;
    if (instrumentation != null) {
    //履行oncreate
            instrumentation.callApplicationOnCreate(app);
    }
    return app;
}
//调用Application的onCreate函数
public void callApplicationOnCreate(Application app) {
    app.onCreate();
}
//Instrumentation中创立application
public Application newApplication(ClassLoader cl, String className, Context context)
        throws InstantiationException, IllegalAccessException, 
        ClassNotFoundException {
    Application app = getFactory(context.getPackageName())
            .instantiateApplication(cl, className);
            //调用Application的attach办法
    app.attach(context);
    return app;
}
//回来AppComponentFactory
private AppComponentFactory getFactory(String pkg) {
    if (pkg == null) {
        Log.e(TAG, "No pkg specified, disabling AppComponentFactory");
        return AppComponentFactory.DEFAULT;
    }
    if (mThread == null) {
        Log.e(TAG, "Uninitialized ActivityThread, likely app-created Instrumentation,"
                + " disabling AppComponentFactory", new Throwable());
        return AppComponentFactory.DEFAULT;
    }
    //之前在handlebindApplication 现已存入了 现在获取出来apk
    LoadedApk apk = mThread.peekPackageInfo(pkg, true);
    if (apk == null) apk = mThread.getSystemContext().mPackageInfo;
    return apk.getAppFactory();
}
文件目录:/frameworks/base/core/java/android/app/AppComponentFactory.java 
//经过反射创立Application
public @NonNull Application instantiateApplication(@NonNull ClassLoader cl,
        @NonNull String className)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (Application) cl.loadClass(className).newInstance();
}
final void attach(Context context) {
    attachBaseContext(context);//调用attachBaseContext
    //拿到mLoadedApk
    mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

代码有点多,总体的流程是在ActivityThread的main中创立了ActivityThread以及调用了attach函数,经过IPC调用到AMSattachApplication把pid等信息存入到mPidsSelefLocked中,然后IPC调用 告诉使用bindApplication把一些数据回来,在bindApplication之后再调用ATMSInternalattachApplication敞开activity。在ActivityThread的handleBindApplication中 再经过Instrumentation反射创立了Application,调用attachcallApplicationOnCreate履行Application的生命周期

attemptZygoteSendArgsAndGetResult 办法中 设置了result的pid以及usingWrapper`。

总结

图片总结

AMS的发动流程图

【Android Framework】ActivityManagerService(一)

AMS创立进程的流程图

【Android Framework】ActivityManagerService(一)

Launcer AMS zygote ActivityThread的交互图

【Android Framework】ActivityManagerService(一)

在线视频(一):

www.bilibili.com/video/BV18T…

在线视频(二):

www.bilibili.com/video/BV1nV…