Android 应用是如何启动的?,最新出炉

本文详细解析了Android启动过程中Zygote如何创建并forkSystemServer,以及SystemServer如何初始化关键服务,如ActivityTaskManagerService、ActivityManagerService等,展示了Android框架中的重要进程和服务初始化流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

}

注释1:预加载资源。

注释2:创建Zygote 的 LocalServerSocket 。

注释3:开始fork我们的SystemServer进程。

注释4:zygote 永久循环。

这里咱们看看 forkSystemServer() ;

1.3.2 forkSystemServer()

/**

* Prepare the arguments and forks for the system server process.

* @return A {@code Runnable} that provides an entrypoint into system_server code in the child

* process; {@code null} in the parent.

*/

private static Runnable forkSystemServer(String abiList, String socketName,

ZygoteServer zygoteServer) {

//命令行来启动SystemServer

//ZygoteInit.main(String argv[])里面的argv 跟这个类似

String[] args = {

“–setuid=1000”,

“–setgid=1000”,

“–setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,”

+ “1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011”,

“–capabilities=” + capabilities + “,” + capabilities,

“–nice-name=system_server”,

“–runtime-args”,

“–target-sdk-version=” + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,

“com.android.server.SystemServer”,

};

//处理与 zygote spawner 相关的 args 的参数解析。

ZygoteArguments parsedArgs;

int pid;

try {

ZygoteCommandBuffer commandBuffer = new ZygoteCommandBuffer(args);

try {

parsedArgs = ZygoteArguments.getInstance(commandBuffer);

} catch (EOFException e) {

throw new AssertionError(“Unexpected argument error for forking system server”, e);

}

commandBuffer.close();

//请求 fork 系统服务器进程

/* Request to fork the system server process */

pid = Zygote.forkSystemServer(

parsedArgs.mUid, parsedArgs.mGid,

parsedArgs.mGids,

parsedArgs.mRuntimeFlags,

null,

parsedArgs.mPermittedCapabilities,

parsedArgs.mEffectiveCapabilities);

} catch (IllegalArgumentException ex) {

throw new RuntimeException(ex);

}

/* For child process */

if (pid == 0) {

if (hasSecondZygote(abiList)) {

waitForSecondaryZygote(socketName);

}

zygoteServer.closeServerSocket();

return handleSystemServerProcess(parsedArgs);

}

return null;

}

这里启动了一个 system server 。下面咱们就看看他。

2、SystemServer

==============

system server 也就是 SystemServer。SystemServer也是一个进程,包括ActivityTaskManagerService、ActivityManagerService、PackageManagerService、WindowManagerService等92种服务。

Android Framework里面两大非常重要的进程:

  • SystemServer进程。

  • Zygote进程。

2.1 SystemServer.java


frameworks/base/services/java/com/android/server/SystemServer.java

public final class SystemServer {

}

2.1.1 main()

/**

* The main entry point from zygote.

*/

public static void main(String[] args) {

new SystemServer().run();

}

public SystemServer() {

// Check for factory test mode.

mFactoryTestMode = FactoryTest.getMode();

}

下面 咱们看看 run () 里面都用什么?

2.1.2 run()

private void run() {

try {

// 注释1:加载动态库libandroid_service.so。

System.loadLibrary(“android_servers”);

// 注释2:创建系统上下文。

createSystemContext();

// 调用每个进程的主线模块初始化。

ActivityThread.initializeMainlineModules();

// 注释3:创建 SystemServiceManager。

mSystemServiceManager = new SystemServiceManager(mSystemContext);

mSystemServiceManager.setStartInfo(mRuntimeRestart,

mRuntimeStartElapsedTime, mRuntimeStartUptime);

LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// 为可并行化的 init 任务准备线程池

SystemServerInitThreadPool.start();

} finally {

}

// 注释4:Start services。

try {

//下面咱们看看这个三个方法启动什么服务

startBootstrapServices(t);

startCoreServices(t);

startOtherServices(t);

} catch (Throwable ex) {

} finally {

t.traceEnd(); // StartServices

}

// 注释5:Loop 永久循环。

Looper.loop();

throw new RuntimeException(“Main thread loop unexpectedly exited”);

}

注释1:加载动态库libandroid_service.so。

注释2:创建系统上下文。

注释3:创建 SystemServiceManager。

注释4:启动服务(startBootstrapServices、startCoreServices、startOtherServices)

注释5:Loop 永久循环。

2.1.3 createSystemContext()

private void createSystemContext() {

ActivityThread activityThread = ActivityThread.systemMain();

mSystemContext = activityThread.getSystemContext();

mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

final Context systemUiContext = activityThread.getSystemUiContext();

systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);

}

初始化系统上下文对象mSystemContext,并设置默认的主题,mSystemContext实际上是一个Context(ContextImpl)对象。

调用ActivityThread.systemMain()的时候,会调用ActivityThread.attach(true),而在attach()里面,则创建了Application对象,并调用了Application.onCreate()。

2.1.4 startBootstrapServices()

/**

* 启动系统引导服务,因为这些服务之间有复杂的相互依赖关系,所以都放在了这个方法里面。

*/

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {

final String TAG_SYSTEM_CONFIG = “ReadingSystemConfig”;

SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

// PlatformCompat Service 由 ActivityManagerService, PackageManagerService 和 其他服务做使用

PlatformCompat platformCompat = new PlatformCompat(mSystemContext);

ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);

ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,

new PlatformCompatNative(platformCompat));

AppCompatCallbacks.install(new long[0]);

mSystemServiceManager.startService(FileIntegrityService.class);

Installer installer = mSystemServiceManager.startService(Installer.class);

mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);

startMemtrackProxyService();

// StartActivityManager

ActivityTaskManagerService atm = mSystemServiceManager.startService(

ActivityTaskManagerService.Lifecycle.class).getService();

//初始化 ActivityManagerService

mActivityManagerService = ActivityManagerService.Lifecycle.startService(

mSystemServiceManager, atm);

mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

mActivityManagerService.setInstaller(installer);

mWindowManagerGlobalLock = atm.getGlobalLock();

mDataLoaderManagerService = mSystemServiceManager.startService(

DataLoaderManagerService.class);

mIncrementalServiceHandle = startIncrementalService();

t.traceEnd();

//初始化PowerManagerService(电源服务),需要提前启动,因为其他服务需要它。

mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

mSystemServiceManager.startService(ThermalManagerService.class);

// 电源管理已经开启,ActivityManagerService负责电源管理功能

mActivityManagerService.initPowerManagement();

mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);

mSystemServiceManager.startService(LightsService.class);

// Package manager isn’t started yet; need to use SysProp not hardware feature

if (SystemProperties.getBoolean(“config.enable_sidekick_graphics”, false)) {

mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);

}

// 初始化DisplayManagerService(显示管理器)

mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

// Start the package manager.

try {

mPackageManagerService = PackageManagerService.main(mSystemContext, installer,

mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);

} finally {

}

// 现在PackageManagerService已经启动,注册 dex 加载报告器来捕获系统服务加载的任何 dex 文件。

// 这些 dex 文件将由 BackgroundDexOptService 优化。

SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService);

mFirstBoot = mPackageManagerService.isFirstBoot();

mPackageManager = mSystemContext.getPackageManager();

//将AMS等添加到ServiceManager中

mActivityManagerService.setSystemProcess();

if (!mOnlyCore) {

boolean disableOtaDexopt = SystemProperties.getBoolean(“config.disable_otadexopt”,

false);

if (!disableOtaDexopt) {

try {

OtaDexoptService.main(mSystemContext, mPackageManagerService);

} catch (Throwable e) {

} finally {

}

}

}

mSensorServiceStart = SystemServerInitThreadPool.submit(() -> {

TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();

startSensorService();

}, START_SENSOR_SERVICE);

// startBootstrapServices

}

改动比较大的地方:

  • ActivityTaskManagerService(ATMS):负责管理除Activity和进程,包括生命周期和状态切换。

  • ActivityManagerService(AMS):AMN的子类,负责管理三大组件(除Activity)和进程,包括生命周期和状态切换。AMS因为要和ui交互,所以极其复杂,涉及window。

ActivityTaskManagerService:把 Activity 相关的内容从 ActivityManagerService 剥离出来而产生的。

PowerManagerService(PMS):电源管理服务。

PackageManagerService(PKMS):包管理服务,不叫PMS是为了和电源管理服务区分开。

2.1.5 startCoreServices()

/**

* 启动核心服务。

*/

private void startCoreServices(@NonNull TimingsTraceAndSlog t) {

// Service for system config

mSystemServiceManager.startService(SystemConfigService.class);

// Tracks the battery level.  Requires LightService.

mSystemServiceManager.startService(BatteryService.class);

mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);

mSystemServiceManager.startService(NativeTombstoneManagerService.class);

mSystemServiceManager.startService(BugreportManagerService.class);

mSystemServiceManager.startService(GpuService.class);

// startCoreServices

}

2.1.6 startOtherServices()

/**

* 启动其他服务。

*/

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {

final Context context = mSystemContext;

VibratorService vibrator = null;

DynamicSystemService dynamicSystem = null;

IStorageManager storageManager = null;

NetworkManagementService networkManagement = null;

IpSecService ipSecService = null;

VpnManagerService vpnManager = null;

VcnManagementService vcnManagement = null;

NetworkStatsService networkStats = null;

NetworkPolicyManagerService networkPolicy = null;

NsdService serviceDiscovery = null;

WindowManagerService wm = null;

SerialService serial = null;

NetworkTimeUpdateService networkTimeUpdater = null;

InputManagerService inputManager = null;

TelephonyRegistry telephonyRegistry = null;

ConsumerIrService consumerIr = null;

MmsServiceBroker mmsService = null;

HardwarePropertiesManagerService hardwarePropertiesService = null;

PacProxyService pacProxyService = null;

// 现在便可以开始启动三方APP应用(如Launcher启动桌面)

mActivityManagerService.systemReady(() -> {

}, t);

// startOtherServices

}

经过上面这些步骤,我们调用调用createSystemContext()创建系统上下文的时候,也已经完成了mSystemContext和ActivityThread的创建。

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
img

便可以开始启动三方APP应用(如Launcher启动桌面)

mActivityManagerService.systemReady(() -> {

}, t);

// startOtherServices

}

经过上面这些步骤,我们调用调用createSystemContext()创建系统上下文的时候,也已经完成了mSystemContext和ActivityThread的创建。

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-PQBA6t6n-1710915860574)]
[外链图片转存中…(img-hreK6FV2-1710915860575)]
[外链图片转存中…(img-Fxn9Qxdv-1710915860576)]
[外链图片转存中…(img-26YoAZQH-1710915860576)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
[外链图片转存中…(img-LfkR35rt-1710915860577)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值