Android Activity---launcher启动流程(一 Zyzote篇)--(Android 12

private void run() {

try {
 	.....
 	//创建消息looper
    Looper.prepareMainLooper();
    Looper.getMainLooper().setSlowLogThresholdMs(
            SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

    SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
	
    // Initialize native services.------------------------1. 加载动态库libAndroid_servers.so
    System.loadLibrary("android_servers");

    // Allow heap / perf profiling.
    initZygoteChildHeapProfiling();

    // Debug builds - spawn a thread to monitor for fd leaks.
    if (Build.IS_DEBUGGABLE) {
        spawnFdLeakCheckThread();
    }

    // Check whether we failed to shut down last time we tried.
    // This call may not return.
    performPendingShutdown();

    // Initialize the system context.----------------------------2. 创建系统的context
    createSystemContext();

    // Call per-process mainline module initialization.
    ActivityThread.initializeMainlineModules();

    // Sets the dumper service
    ServiceManager.addService("system_server_dumper", mDumper);
    mDumper.addDumpable(this);

    // Create the system service manager.-----------------------------------3.  对系统服务进行创建、启动、生命周期管理
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    mSystemServiceManager.setStartInfo(mRuntimeRestart,
            mRuntimeStartElapsedTime, mRuntimeStartUptime);
    mDumper.addDumpable(mSystemServiceManager);

    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    // Prepare the thread pool for init tasks that can be parallelized
    SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
    mDumper.addDumpable(tp);

    // Load preinstalled system fonts for system server, so that WindowManagerService, etc
    // can start using Typeface. Note that fonts are required not only for text rendering,
    // but also for some text operations (e.g. TextUtils.makeSafeForPresentation()).
    if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
        Typeface.loadPreinstalledSystemFontMap();
    }

    // Attach JVMTI agent if this is a debuggable build and the system property is set.
    if (Build.IS_DEBUGGABLE) {
        // Property is of the form "library_path=parameters".
        String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
        if (!jvmtiAgent.isEmpty()) {
            int equalIndex = jvmtiAgent.indexOf('=');
            String libraryPath = jvmtiAgent.substring(0, equalIndex);
            String parameterList =
                    jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
            // Attach the agent.
            try {
                Debug.attachJvmtiAgent(libraryPath, parameterList, null);
            } catch (Exception e) {
                Slog.e("System", "*************************************************");
                Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
            }
        }
    }
} finally {
    t.traceEnd();  // InitBeforeStartServices
}

// Setup the default WTF handler
RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

// Start services.
try {
    t.traceBegin("StartServices");
    //---------------------------------------------------4. 引导服务: 对创建的系统服务ActivityManagerService,pms,powermanagerservice等服务进行 创建,启动、生命周期管理等
    startBootstrapServices(t);
    //--------------------------------------------------- 5.核心服务:启动SystemConfigService,BatteryService等
    startCoreServices(t);
   //--------------------------------------------------- 6.其他服务:启动DynamicSystemService,NetworkManagementService,DropBoxManagerService
   
    startOtherServices(t);
} catch (Throwable ex) {
    Slog.e("System", "******************************************");
    Slog.e("System", "************ Failure starting system services", ex);
    throw ex;
} finally {
    t.traceEnd(); // StartServices
}

StrictMode.initVmDefaults(null);

if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
    final long uptimeMillis = SystemClock.elapsedRealtime();
    FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
            FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
            uptimeMillis);
    final long maxUptimeMillis = 60 * 1000;
    if (uptimeMillis > maxUptimeMillis) {
        Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
                "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
    }
}

// Loop forever.-------loop循环取消息,ActivityThread的loop不允许quit()方法调用 退出
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");

}


下图列出一些服务的含义


##### 3.1.1、引导服务:图3.0


在他里面刚开始就是我们常说的**Watchdog**


![image.png](https://img-blog.csdnimg.cn/img_convert/bed4db1b87d894761859218589bbd3ba.png) ​ 图3.0


##### 3.1.2、核心服务:图3.1


![image.png](https://img-blog.csdnimg.cn/img_convert/179f499b8bcb09480f2255223bb02c2a.png)


图3.1


##### 3.1.3、其他服务:图3.2


![image.png](https://img-blog.csdnimg.cn/img_convert/1c3363f9e99365e4e478e7b910393854.png)


图3.2


##### 3.1.4、SystemServer的流程总结


1. 启动binder线程池,这样可以与其他进程进行通信
2. 创建SystemServiceManager,其用于对系统服务进行 创建,启动、生命周期管理等
3. 启动各种系统服务


#### 3.2、launcher启动过程


##### 3.2.1、Android 12.0启动流程图如下



// We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(() -> {

}, t);


流程图:


##### 3.2.2、**[ActivityTaskManagerService.java] startHomeOnAllDisplays()**


\*\*说明:\*\*ActivityTaskManagerInternal是 ActivityManagerService的一个抽象类,正在的实现是在ActivityTaskManagerService的LocalService,所以mAtmInternal.startHomeOnAllDisplays()最终调用的是ActivityTaskManagerService的startHomeOnAllDisplays()方法



@Override
public boolean startHomeOnAllDisplays(int userId, String reason) {
synchronized (mGlobalLock) {
return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
}
}


##### **3.2.3、 [RootWindowContainer.java] startHomeOnAllDisplays()-》startHomeOnDisplay**


\*\*说明:\*\*在[4.1]中,获取的displayId为DEFAULT\_DISPLAY, 首先通过getHomeIntent 来构建一个category为CATEGORY\_HOME的Intent,表明是Home Activity;然后通过resolveHomeActivity()从系统所用已安装的引用中,找到一个符合HomeItent的Activity,最终调用startHomeActivity()来启动Activity



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

}


\*\*说明:\*\*承接startHomeOnDisplay方法



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;

// --------------------------------------------------------------1. 构建一个category为CATEGORY_HOME的Intent
if (taskDisplayArea == getDefaultTaskDisplayArea()) {
    homeIntent = mService.ge
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值