经典网站源码,通化好的网站建设的公司,东莞市建设工程监督网,货源之家官网首语 
SystemServer进程主要用于启动系统服务#xff0c;诸如AMS、WMS、PMS都是由它来创建的。在系统的名称为system_server#xff0c;Android核心服务都是它启动#xff0c;它是非常重要。 
Zygote处理SystemServer进程 
在 Zygote启动过程 文章中分析我们知道…首语 
SystemServer进程主要用于启动系统服务诸如AMS、WMS、PMS都是由它来创建的。在系统的名称为system_serverAndroid核心服务都是它启动它是非常重要。 
Zygote处理SystemServer进程 
在 Zygote启动过程 文章中分析我们知道调用Zygote的forkSystemServer方法启动SystemServer进程。 
调用nativeZygoteInit方法它是Native层的代码用来启动Binder线程池这样SystemServer进程就可以使用Binder与其它进程进行通信。 
调用applicationInit方法通过反射得到SystemServer类className为com.android.server.SystemServer然后找到SystemServer类 的main方法。传入MethodAndArgsCaller类并返回给ZygoteInit类的main方法。调用MethodAndArgsCaller类的run方法MethodAndArgsCaller类是RuntimeInit类的静态类。最后动态调用SystemServer的main方法。 
源码路径frameworks/base/core/java/com/android/internal/os/ZygoteInit.java 
private static Runnable forkSystemServer(String abiList, String socketName,ZygoteServer zygoteServer) {...if (pid  0) {if (hasSecondZygote(abiList)) {waitForSecondaryZygote(socketName);}zygoteServer.closeServerSocket();//处理SystemServer进程return handleSystemServerProcess(parsedArgs);}
}
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {...ClassLoader cl  getOrCreateSystemServerClassLoader();if (cl ! null) {Thread.currentThread().setContextClassLoader(cl);}//Pass the remaining arguments to SystemServer.return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,parsedArgs.mDisabledCompatChanges,parsedArgs.mRemainingArgs, cl);    
}public static Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,String[] argv, ClassLoader classLoader) {if (RuntimeInit.DEBUG) {Slog.d(RuntimeInit.TAG, RuntimeInit: Starting application from zygote);}Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, ZygoteInit);RuntimeInit.redirectLogStreams();RuntimeInit.commonInit();//启动Binder线程池ZygoteInit.nativeZygoteInit();//进入SystemServer的main方法return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,classLoader);
}
public static void main(String[] argv) {...if (startSystemServer) {Runnable r  forkSystemServer(abiList, zygoteSocketName, zygoteServer);// {code r  null} in the parent (zygote) process, and {code r ! null} in the// child (system_server) process.//MethodAndArgsCaller.run方法if (r ! null) {r.run();return;}}  
}源码路径frameworks/base/core/java/com/android/internal/os/RuntimeInit.java 
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,String[] argv, ClassLoader classLoader) {...// Remaining arguments are passed to the start classs static mainreturn findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv,ClassLoader classLoader) {Class? cl;try {//反射得到SystemServer类cl  Class.forName(className, true, classLoader);} catch (ClassNotFoundException ex) {throw new RuntimeException(Missing class when invoking static main   className,ex);}Method m;try {//知道main方法m  cl.getMethod(main, new Class[] { String[].class });} catch (NoSuchMethodException ex) {throw new RuntimeException(Missing static main on   className, ex);} catch (SecurityException ex) {throw new RuntimeException(Problem getting static main on   className, ex);}int modifiers  m.getModifiers();if (! (Modifier.isStatic(modifiers)  Modifier.isPublic(modifiers))) {throw new RuntimeException(Main method is not public and static on   className);}/** This throw gets caught in ZygoteInit.main(), which responds* by invoking the exceptions run() method. This arrangement* clears up all the stack frames that were required in setting* up the process.*/return new MethodAndArgsCaller(m, argv);
}
static class MethodAndArgsCaller implements Runnable {/** method to call */private final Method mMethod;/** argument array */private final String[] mArgs;public MethodAndArgsCaller(Method method, String[] args) {mMethod  method;mArgs  args;}public void run() {try {//动态调用SystemServer的main方法mMethod.invoke(null, new Object[] { mArgs });} catch (IllegalAccessException ex) {throw new RuntimeException(ex);} catch (InvocationTargetException ex) {Throwable cause  ex.getCause();if (cause instanceof RuntimeException) {throw (RuntimeException) cause;} else if (cause instanceof Error) {throw (Error) cause;}throw new RuntimeException(ex);}}
}解析SystemServer进程 
main方法调用了SystemServer的run方法在run方法里首先进行了一些系统属性的设置、加载动态库及创建系统的Context。然后创建了SystemServiceManager它会对系统服务进行创建、管理和生命周期管理。接下来有四个关键方法。 
startBootstrapServices(t)。启动引导服务。共启动了约25个引导服务。例如我们熟知的AMS、PMS等服务。其中主要创建引导服务及作用如下(所有服务查看对应方法) 
引导服务作用Installer系统安装APK时候的一个服务类启用完成Installer服务后才能启动其它的系统服务ActivityManagerService负责四大组件的启动、切换、调度PowerManagerServiceAndroid系统中和Power相关的计算决策系统电影策略LightService管理和显示背光LEDDisplayManagerService管理所有显示设备PackageManagerService对APK进行安装、解析、验签、卸载等操作UserManagerService多用户模式管理服务SensorServiceAndroid各种感应器服务…… 
startCoreServices(t)。启动核心服务。共启动了约11个核心服务。主要核心服务及作用如下(所有服务查看对应方法) 
核心服务作用BatteryService管理电池相关服务UsageStatsService收集用户使用App的频率、使用时长WebViewUpdateServiceWebview更新服务BugreportManagerServicebugreport的管理服务GpuService管理GPU资源的服务…… 
startOtherServices(t)。启动其它服务。它启动了多达几十种服务。大多是我们使用设备功能息息相关的服务。主要其它服务及作用如下(所有服务查看对应方法) 
其它服务作用AlarmManagerService定时器管理服务InputManagerService输入事件管理服务CameraServiceProxy摄像相关服务WindowManagerService窗口管理服务VrManagerServiceVR模式管理服务BluetoothService蓝牙管理服务NotificationManagerService通知管理服务StorageManagerService存储管理服务LocationManagerService定位管理服务AudioService音频管理服务…… 
在这个方法里可以看到服务启动的多个阶段标志如PHASE_SYSTEM_SERVICES_READY/PHASE_DEVICE_SPECIFIC_SERVICES_READY等。其中PHASE_BOOT_COMPLETED1000;标志着完成了Android开机启动流程。系统服务更倾向于监听该阶段而不是注册广播BOOT_COMPLETED从而降低系统延迟。 
startApexServices(t)。启动Apex服务。 Apex服务是指Android操作系统中的一种应用程序启动方式它允许应用程序在设备启动时以系统服务的形式自动运行。这些服务通常包括系统应用、框架服务和系统UI等。它们在设备启动时会自动运行并为用户提供各种基础功能和界面。 startApexServices方法会遍历所有已安装的Apex服务并调用它们的启动方法使它们在系统启动时自动运行。该方法在系统启动过程中被调用是Android操作系统启动过程中的一部分。 从这里我们也能看出来官方将系统服务分为了以上四种。它们启动方法相似。通过SystemServiceManager类的startService方法启动。我们以PowerManagerService为例进行分析如何启动。 
startService中调用PowerManagerService类的onStart方法完成启动PowerManagerService。 
除了通过SystemServiceManager类的startService方法启动外还有通过对应Service的main方法启动例如PackageManagerService。 
由源码可知PackageManagerService被注册到ServiceManager中。ServiceManager用来管理系统的各种Service这些服务通过Binder通信机制与应用程序进行通信。 
源码路径frameworks/base/services/java/com/android/server/SystemServer.java 
public static void main(String[] args) {new SystemServer().run();
}
private void run() {TimingsTraceAndSlog t  new TimingsTraceAndSlog();try {...//创建消息LooperLooper.prepareMainLooper();Looper.getMainLooper().setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);SystemServiceRegistry.sEnableServiceNotFoundWtf  true;// 加载动态库libandroid_servers.soSystem.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();// 创建系统ContextcreateSystemContext();// Call per-process mainline module initialization.ActivityThread.initializeMainlineModules();// Sets the dumper serviceServiceManager.addService(system_server_dumper, mDumper);mDumper.addDumpable(this);// 创建SystemServiceManager对系统服务进行创建、启动和生命周期管理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 parallelizedSystemServerInitThreadPool tp  SystemServerInitThreadPool.start();mDumper.addDumpable(tp);...} finally {t.traceEnd();  // InitBeforeStartServices}// Setup the default WTF handlerRuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);// Start services.try {t.traceBegin(StartServices);//启动引导服务startBootstrapServices(t);//启动核心服务startCoreServices(t);//启动其它服务startOtherServices(t);//启动Apex服务startApexServices(t);} catch (Throwable ex) {Slog.e(System, ******************************************);Slog.e(System, ************ Failure starting system services, ex);throw ex;} finally {t.traceEnd(); // StartServices}...}
private void startBootstrapServices(NonNull TimingsTraceAndSlog t) {...//启动AMSActivityTaskManagerService-ActivityManagerServicet.traceBegin(StartActivityManager);ActivityTaskManagerService atm  mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();mActivityManagerService  ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setInstaller(installer);mWindowManagerGlobalLock  atm.getGlobalLock();t.traceEnd();t.traceBegin(StartPowerManager);mPowerManagerService  mSystemServiceManager.startService(PowerManagerService.class);t.traceEnd();t.traceBegin(StartPackageManagerService);try {Watchdog.getInstance().pauseWatchingCurrentThread(packagemanagermain);PairPackageManagerService, IPackageManager pmsPair  PackageManagerService.main(mSystemContext, installer, domainVerificationService,mFactoryTestMode ! FactoryTest.FACTORY_TEST_OFF, mOnlyCore);mPackageManagerService  pmsPair.first;iPackageManager  pmsPair.second;} finally {Watchdog.getInstance().resumeWatchingCurrentThread(packagemanagermain);}...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);...
}
private void startOtherServices(NonNull TimingsTraceAndSlog t) {...// WMS needs sensor service readymSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);...mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);}
private void startApexServices(NonNull TimingsTraceAndSlog t) {ListApexSystemServiceInfo services  ApexManager.getInstance().getApexSystemServices();for (ApexSystemServiceInfo info : services) {String name  info.getName();String jarPath  info.getJarPath();t.traceBegin(starting   name);if (TextUtils.isEmpty(jarPath)) {mSystemServiceManager.startService(name);} else {mSystemServiceManager.startServiceFromJar(name, jarPath);}t.traceEnd();}
}源码路径frameworks/base/services/core/java/com/android/server/SystemServiceManager.java 
public void startService(NonNull final SystemService service) {// Check if already startedString className  service.getClass().getName();if (mServiceClassnames.contains(className)) {Slog.i(TAG, Not starting an already started service   className);return;}mServiceClassnames.add(className);// Register it.mServices.add(service);// Start it.long time  SystemClock.elapsedRealtime();try {//启动serviceservice.onStart();} catch (RuntimeException ex) {throw new RuntimeException(Failed to start service   service.getClass().getName() : onStart threw an exception, ex);}warnIfTooLong(SystemClock.elapsedRealtime() - time, service, onStart);
}
//系统服务启动指定的启动阶段
public void startBootPhase(NonNull TimingsTraceAndSlog t, int phase) {if (phase  mCurrentPhase) {throw new IllegalArgumentException(Next phase must be larger than previous);}mCurrentPhase  phase;Slog.i(TAG, Starting phase   mCurrentPhase);try {t.traceBegin(OnBootPhase_  phase);final int serviceLen  mServices.size();for (int i  0; i  serviceLen; i) {final SystemService service  mServices.get(i);long time  SystemClock.elapsedRealtime();t.traceBegin(OnBootPhase_  phase  _  service.getClass().getName());try {//系统服务的onBootPhase方法service.onBootPhase(mCurrentPhase);} catch (Exception ex) {throw new RuntimeException(Failed to boot service  service.getClass().getName() : onBootPhase threw an exception during phase  mCurrentPhase, ex);}warnIfTooLong(SystemClock.elapsedRealtime() - time, service, onBootPhase);t.traceEnd();}} finally {t.traceEnd();}//开机阶段if (phase  SystemService.PHASE_BOOT_COMPLETED) {final long totalBootTime  SystemClock.uptimeMillis() - mRuntimeStartUptime;t.logDuration(TotalBootTime, totalBootTime);SystemServerInitThreadPool.shutdown();}
}
public boolean isBootCompleted() {return mCurrentPhase  SystemService.PHASE_BOOT_COMPLETED;
}源码路径frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java 
public static PairPackageManagerService, IPackageManager main(Context context,Installer installer, NonNull DomainVerificationService domainVerificationService,boolean factoryTest, boolean onlyCore) {...PackageManagerService m  new PackageManagerService(injector, onlyCore, factoryTest,PackagePartitions.FINGERPRINT, Build.IS_ENG, Build.IS_USERDEBUG,Build.VERSION.SDK_INT, Build.VERSION.INCREMENTAL);...IPackageManagerImpl iPackageManager  m.new IPackageManagerImpl();ServiceManager.addService(package, iPackageManager);...
}SystemServer在启动系统服务存在多个阶段如下所示 源码路径frameworks/base/services/core/java/com/android/server/SystemService.java /*** 系统在引导时向系统服务发送的最早引导阶段。*/public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY  100;/*** 在SensorService可用性上阻塞的引导阶段。该服务是异步启动的因为它可能需要一段时间才能完成初始化。* hide*/public static final int PHASE_WAIT_FOR_SENSOR_SERVICE  200;/*** 在接收这个启动阶段后服务可以获取锁设置数据。*/public static final int PHASE_LOCK_SETTINGS_READY  480;/*** 在收到此启动阶段后服务可以安全地调用核心系统服务*/public static final int PHASE_SYSTEM_SERVICES_READY  500;/*** 在收到此启动阶段后服务可以安全地调用设备特定的服务。*/public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY  520;/*** 在收到此启动阶段后服务可以广播意图。*/public static final int PHASE_ACTIVITY_MANAGER_READY  550;/*** 在收到此启动阶段后服务可以启动/绑定到第三方应用程序。应用程序将能够在此处对服务进行 Binder 调用。*/public static final int PHASE_THIRD_PARTY_APPS_CAN_START  600;/*** 在收到此启动阶段后服务允许用户与设备进行交互。此阶段发生在启动完成且主应用程序已启动时。系统服务可能更倾向于监听此阶	   * 段而不是注册ACTION_LOCKED_BOOT_COMPLETED减少整体延迟。*/public static final int PHASE_BOOT_COMPLETED  1000;总结 
Zygote调用startSystemServer创建SystemServer进程。SystemServer进程启动了各种系统服务(四种)并且SystemServer在启动系统服务有定义多个阶段。SystemServiceManager对系统服务进行管理。