Android-33源码分析: 系统启动流程

1、按下电源键进行系统启动:触发引导芯片,加载预定义代码,启动引导程序BootLoader
2、启动BootLoader引导程序:它是一个Android系统启动前运行的一个小程序,用来拉起OS并运行
3、启动linux内核:设置缓存、被保护存储器、计划列表、加载驱动、完成系统设置,设置完后会找到系统文件init.rc启动init进程
init_parse_config_file("/init.rc");
4、启动init进程:初始化并启动属性服务,启动zygote进程
Zygote进程的初始化在App_main.cpp文件中开启
  // 使用运行时环境启动Zygote的初始化类.
  runtime.start("com.android.internal.os.ZygoteInit", startSystemServer);
5、启动zygote进程孵化器:创建JVM,注册JNI,创建服务端的socket,启动systemServer进程
6、启动systemServer进程:启动binder线程池和systemServerManager,启动各种系统服务,如AMS、WMS等
现在从c或c++代码进入到java代码中, ZygoteInit.java初始化类
public static void main(String[] argv) {
....
// 孵化器fork出SystemServer类
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer)
....
}
    static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        ZygoteHooks.preFork();
      
        int pid = nativeForkSystemServer(
                uid, gid, gids, runtimeFlags, rlimits,
                permittedCapabilities, effectiveCapabilities);

        // Set the Java Language thread priority to the default value for new apps.
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

        ZygoteHooks.postForkCommon();
        return pid;
    }
    //  com.android.server.SystemServer 

    // 执行main方法
    public static void main(String[] args) {
        new SystemServer().run();
    }


  private void run() {
        TimingsTraceAndSlog t = new TimingsTraceAndSlog();
        /**
         * 该进程中也会维护一个主Looper循环 并开启消息循环Looper.loop()
         */
        // Start services.
        try {
            t.traceBegin("StartServices");
            // 启动引导服务
            startBootstrapServices(t);
            // 启动核心服务
            startCoreServices(t);
            // 启动其他服务-会执行mActivityManagerService.systemReady()
            startOtherServices(t);

            startApexServices(t);
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }

        // Loop forever.
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
// 启动引导服务
DeviceIdentifiersPolicyService
UriGrantsManagerService
PowerStatsService
ActivityTaskManagerService   
ActivityManagerService
DataLoaderManagerService
PowerManagerService
ThermalManagerService
HintManagerService
RecoverySystemService
DisplayManagerService
UserManagerService
OverlayManagerService
ResourcesManagerService
....
// 启动核心服务
SystemConfigService
BatteryService
UsageStatsService
WebViewUpdateService
CachedDeviceStateService
BinderCallsStatsService
GpuService
...
// 启动其他服务
BinaryTransparencyService
DropBoxManagerService
VibratorManagerService
WindowManagerService
NetworkManagementService
NetworkWatchlistService
FontManagerService
PinnerService
LogcatManagerService
....
    /**
     * Ready. Set. Go!
     * ActivityTaskManagerInternal是ActivityManagerService的抽象类
     * 实现是ActivityTaskManagerService的LocalService,
     * 所以mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady")
     * 最终调用的是ActivityTaskManagerService的startHomeOnAllDisplays()方法
     */
    public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
    ...省略

     if (bootingSystemUser) {
                t.traceBegin("startHomeOnAllDisplays");
                mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
                t.traceEnd();
            }

     ...省略

    }

ActivityTaskManagerService 中方法调用
        @Override
        public boolean startHomeOnAllDisplays(int userId, String reason) {
            synchronized (mGlobalLock) {
                return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
            }
        }
RootWindowContainer 中方法调用

    boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
            boolean fromHomeKey) {
        // Fallback to top focused display or default display if the displayId is invalid.
        if (displayId == INVALID_DISPLAY) {
            final Task rootTask = getTopDisplayFocusedRootTask();
            displayId = rootTask != null ? rootTask.getDisplayId() : DEFAULT_DISPLAY;
        }

        final DisplayContent display = getDisplayContent(displayId);
        return display.reduceOnAllTaskDisplayAreas((taskDisplayArea, result) ->
                        result | startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea,
                                allowInstrumenting, fromHomeKey),
                false /* initValue */);
    }

  boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
            boolean allowInstrumenting, boolean fromHomeKey) {
        // Fallback to top focused display area if the provided one is invalid.
        if (taskDisplayArea == null) {
            final Task rootTask = getTopDisplayFocusedRootTask();
            taskDisplayArea = rootTask != null ? rootTask.getDisplayArea()
                    : getDefaultTaskDisplayArea();
        }

        Intent homeIntent = null;
        ActivityInfo aInfo = null;
        if (taskDisplayArea == getDefaultTaskDisplayArea()) {
            // 配置意图同时设置CATEGORY_HOME
            homeIntent = mService.getHomeIntent();
            aInfo = resolveHomeActivity(userId, homeIntent);
        } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
            Pair info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
            aInfo = info.first;
            homeIntent = info.second;
        }
        if (aInfo == null || homeIntent == null) {
            return false;
        }
        // 检查能否正常显示
        if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) {
            return false;
        }

        // Updates the home component of the intent.
        homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
        homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
        // Updates the extra information of the intent.
        if (fromHomeKey) {
            homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
            if (mWindowManager.getRecentsAnimationController() != null) {
                mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart();
            }
        }
        homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason);

        // Update the reason for ANR debugging to verify if the user activity is the one that
        // actually launched.
        final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
                aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
        mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
                taskDisplayArea);
        return true;
    }
ActivityStartController 中方法调用
    void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason,
            TaskDisplayArea taskDisplayArea) {
        // ...省略
        // 执行ActivityStarter中的execute
        mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
                .setOutActivity(tmpOutRecord)
                .setCallingUid(0)
                .setActivityInfo(aInfo)
                .setActivityOptions(options.toBundle())
                .execute();
        mLastHomeActivityStartRecord = tmpOutRecord[0];
        if (rootHomeTask.mInResumeTopActivity) {
            // If we are in resume section already, home activity will be initialized, but not
            // resumed (to avoid recursive resume) and will stay that way until something pokes it
            // again. We need to schedule another resume.
            mSupervisor.scheduleResumeTopActivities();
        }
    }
ActivityStarter // 负责界面启动检查
.execute()
.executeRequest(mRequest)
.startActivityUnchecked(final ActivityRecord r....)
.startActivityInner(final ActivityRecord r....)
mRootWindowContainer.resumeFocusedTasksTopActivities(mTargetRootTask....)

RootWindowContainer
.resumeFocusedTasksTopActivities(mTargetRootTask, mStartActivity, mOptions, mTransientLaunch)
targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions, deferPause)

Task
.resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause)
.resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause)
topFragment.resumeTopActivity(prev, options, deferPause)

TaskFragment
.resumeTopActivity(ActivityRecord prev, ActivityOptions options, boolean deferPause)
mTaskSupervisor.startSpecificActivity(next, true, true)

ActivityTaskSupervisor // 负责所有Activity栈的管理
.startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig)
.realStartActivityLocked(r, wpc, andResume, checkConfig)
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent)....) // 解释LaunchActivityItem由来
mService.getLifecycleManager().scheduleTransaction(clientTransaction)

ClientLifecycleManager // 生命周期的管理调用
.scheduleTransaction(ClientTransaction transaction)
transaction.schedule();

ClientTransaction  // 客服端事务调度
.schedule()
IApplicationThread=mClient.scheduleTransaction(this)

ActivityThread 内部类 ApplicationThread // ApplicationThread 实现IApplicationThread
.scheduleTransaction(ClientTransaction transaction)
ActivityThread.this.scheduleTransaction(transaction)

ClientTransactionHandler // ActivityThread的父类 主要管理消息发送与执行
.scheduleTransaction(ClientTransaction transaction)
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);

ActivityThread.mH // mH是ActivityThread内部Handler
TransactionExecutor=mTransactionExecutor.execute(transaction)

TransactionExecutor // 主要作用是执行ClientTransaction
.execute(ClientTransaction transaction)
.executeLifecycleState(ClientTransaction transaction)
lifecycleItem.execute(mTransactionHandler, token, mPendingActions)

LaunchActivityItem // 继承自ClientTransactionItem,而ClientTransactionItem实现BaseClientRequest  // ResumeActivityItem
.execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions)
ClientTransactionHandler=client.handleLaunchActivity(r, pendingActions, null /* customIntent */)

ActivityThread ex ClientTransactionHandler // 管理应用程序进程中主线程的执行
.handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent)
.performLaunchActivity(r, customIntent)
Instrumentation=mInstrumentation.callActivityOnCreate(activity....)

Instrumentation
.callActivityOnCreate(activity....)
activity.performCreate(icicle)

Activity
.performCreate(Bundle icicle)
.performCreate(Bundle icicle, PersistableBundle persistentState)
.onCreate(icicle....)
应用进程的创建:
ActivityTaskSupervisor
mService.startProcessAsync(r, knownToBeDead...)

ActivityTaskManagerService
.startProcessAsync(r, knownToBeDead...)
Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess...)
ActivityManagerInternal抽象类实现ActivityManagerService.LocalService

ActivityManagerService
.startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,boolean isTop, String hostingType, ComponentName hostingName)
.tartProcessLocked(processName, info.....)
.tartProcessLocked(processName, info.....) // 重载
mProcessList.startProcessLocked(processName, info, knownToBeDead...)

ProcessList
.startProcessLocked(processName, info, knownToBeDead...)
.startProcessLocked(processName, info, knownToBeDead...) // 重载
final Process.ProcessStartResult startResult = startProcess(hostingRecord,entryPoint, app,....)
startResult = appZygote.getProcess().start(entryPoint,app.processName, uid, uid, gids.....)
AppZygote.getProcess返回ChildZygoteProcess继承ZygoteProcess

ZygoteProcess
.start(final String processClass,final String niceName,int uid, int gid, @Nullable int[] gids....)
.startViaZygote(final String processClass,final String niceName,int uid, int gid, @Nullable int[] gids....)
.zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),  zygotePolicyFlags, argsForZygote)
.attemptZygoteSendArgsAndGetResult(zygoteState, msgStr)
zygoteWriter.write(msgStr);  // 把应用进程参数写入zygote进程 比如 processClass ="android.app.ActivityThread"
zygoteWriter.flush(); // 进入Zygote进程,处于阻塞状态
// fork采用copy-on-write机制 

ZygoteInit
.main(String[] argv)
zygoteServer.runSelectLoop(abiList)->caller.run()

ZygoteServer
.runSelectLoop(abiList)
final Runnable command = connection.processCommand(this, multipleForksOK)

ZygoteConnection
.processCommand(ZygoteServer zygoteServer, boolean multipleOK)
handleChildProc(parsedArgs, childPipeFd,parsedArgs.mStartChildZygote)
ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, null /* classLoader */)

ZygoteInit
.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, null /* classLoader */)
RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,classLoader)

RuntimeInit
.applicationInit(int targetSdkVersion, long[] disabledCompatChanges,String[] argv, ClassLoader classLoader)
.indStaticMain(String className, String[] argv,ClassLoader classLoader)
new MethodAndArgsCaller(m, argv).run({mMethod.invoke(null, new Object[] { mArgs })})

ActivityThread.main() 执行完成

你可能感兴趣的:(android)