文章目录
总体流程
在Android系统启动过程中,需要经历几个流程:
- 启动Init进程
- 启动Zygote进程
- 启动SystemService
- 启动Launcher
本文主要了解Zygote进程和SystemService进程启动、系统服务流程。
Zygote进程意思为受精卵进程,由app_process启动。Zygote进程启动之后,会绑定一个端口,作为Socket的Server端,接收着其他进程请求创建> 新的进程。 应用进程通过Binder请求SystemServer进程,SystemServer进程发送socket消息给Zygote进程,最后由Zygote进程创建fork出来的。
SystemServer进程,运行多个服务的线程,应用进程通过Binder使用SystemService中的服务
ZygoteInit
public static void main(String argv[]) {
// 1. 启动 ZygnoteServer
ZygoteServer zygoteServer = new ZygoteServer();
...
Os.setpgid(0, 0);
try {
// 开启ddms
RuntimeInit.enableDdms();
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
// 解析启动参数
boolean enableLazyPreload = false;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
// 2.启动zynote socket
zygoteServer.registerServerSocket(socketName);
// 3.预加载资源
if (!enableLazyPreload) {
preload(bootTimingsTraceLog);
}
...
// 4. 启动 SystemServer
if (startSystemServer) {
startSystemServer(abiList, socketName, zygoteServer);
}
// 5. zygote 启动循环监听
zygoteServer.runSelectLoop(abiList);
// 6. 关闭socket
zygoteServer.closeServerSocket();
}
}
init进程启动的时候,会调用zygoteInit的main方法
总体的流程是:
- 启动一个socket,并循环监听
- 预加载资源
- 启动systemServer
SystemServer
SystemServer 运行在一个独立的进程,其中上面运行了多个系统服务线程。
// ZygoteInit
private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
throws Zygote.MethodAndArgsCaller, RuntimeException {
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
// 线程启动成功
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
// 子线程关闭socket
zygoteServer.closeServerSocket();
handleSystemServerProcess(parsedArgs);
}
return true;
}
Zygote 创建fork一个进程,并启动了SystemServer
// SystemServer
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
try {
// 设置系统化属性
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
SystemProperties.set("persist.sys.timezone", "GMT");
}
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// 启动一个looper
Looper.prepareMainLooper();
// 加载native层的libandroid_servers
// Initialize native services.
System.loadLibrary("android_servers");
// 创建System的context
createSystemContext();
//创建mSystemServiceManager,负责启动系统服务
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
}
// 启动服务
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
}
// 开启循环loop
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
SystemServer启动大致的流程:
- 设置系统时间、属性
- 初始化looper
- 加载native的android_server
- 创建system Context
- 创建mSystemServiceManager
- 启动系统服务
- looper开启循环
SystemServiceManager
顾名思义,SystemServiceManager 负责启动各个具体的SystemService线程
// SystemServiceManager
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
}
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
startService(service);
return service;
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = System.currentTimeMillis();
try {
service.onStart();
} catch (RuntimeException ex) {
}
warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
}
SystemServiceManager启动systemService的历程并不难,主要是通过反射构造出service,再调用service的onStart()方法
这里有个疑问,systemService不是运行在独立的线程吗?
// 启动三种服务
startBootstrapServices();
startCoreServices();
startOtherServices();
系统服务启动分为三类
- startBootstrapServices()
- startCoreServices()
- startOtherServices()
startBootstrapServices:
- 启动Installer服务
- 启动ActivityManagerService,Installer赋给AMS
- 启动PowerManagerService
- 启动LightsService
- 启动PackageManagerService
- 启动SensorService
startCoreServices:
- 启动BatteryService
- 启动UsageStatsService
- AMS setUsageStatsManager
startOtherServices:
- 启动SchedulingPolicyService
- 启动TelecomLoaderService
- 启动TelephonyRegistry
- 启动CameraService
- 启动AccountManagerService
- 启动ContentService
- 启动VibratorService
- 启动ConsumerIrService
- 启动AlarmManagerService
- 初始化WatchDog与AMS相关
- 启动WindowManagerService
- 启动InputManagerService
- 启动AccessibilityManagerService
- 启动LockSettingsService
- 启动DeviceIdleController
- 启动StatusBarManagerService
- 启动ClipboardService
- 启动ConnectivityService
- 启动NotificationManagerService
- 启动JobSchedulerService
- 启动LauncherAppsService
具体来看startBootstrapServices如何启动服务
private void startBootstrapServices() {
Installer installer = mSystemServiceManager.startService(Installer.class);
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
}
我们拿PowerManagerService来看启动服务的流程:
// PowerManagerService
public final class PowerManagerService extends SystemService
implements Watchdog.Monitor {
public PowerManagerService(Context context) {
super(context);
mContext = context;
mHandlerThread = new ServiceThread(TAG,
Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
mHandlerThread.start();
}
启动了一个独立的线程ServiceThread,他是HandlerThread的子类。
// PowerManagerService
@Override
public void onStart() {
publishBinderService(Context.POWER_SERVICE, new BinderService());
publishLocalService(PowerManagerInternal.class, new LocalService());
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
继续发布PowerManagerService
// SystemServer
protected final void publishBinderService(String name, IBinder service) {
publishBinderService(name, service, false);
}
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
protected final <T> void publishLocalService(Class<T> type, T service) {
LocalServices.addService(type, service);
}
WatchDog
在上面有两句代码:
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
watchDog是什么?
WatchDog类作为看门狗来监控SystemServer中的线程。一旦发现问题,WatchDog会杀死SystemServer进程。
SystemServer的父进程Zygote接收到SystemServer的死亡信号后,会杀死自己。Zygote进程死亡的信号传递到Init进程后,Init进程会杀死Zygote进程所有的子进程并重启Zygote。