赞
踩
SystemServer 是android 系统的一个核心服务,它是由Zygote进程fork出来的,负责启动android系统的必要服务,以满足系统和三方应用的基础运行条件。
接Zygote的启动流程继续分析
// TODO 这里,startSystemServer为ture,进入if条件中
if (startSystemServer) {
// 创建systemServer进程并启动它
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
r.run();
return;
}
}
forkSystemServer
private static Runnable forkSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) { long capabilities = posixCapabilitiesAsBits( OsConstants.CAP_IPC_LOCK, OsConstants.CAP_KILL, OsConstants.CAP_NET_ADMIN, OsConstants.CAP_NET_BIND_SERVICE, OsConstants.CAP_NET_BROADCAST, OsConstants.CAP_NET_RAW, OsConstants.CAP_SYS_MODULE, OsConstants.CAP_SYS_NICE, OsConstants.CAP_SYS_PTRACE, OsConstants.CAP_SYS_TIME, OsConstants.CAP_SYS_TTY_CONFIG, OsConstants.CAP_WAKE_ALARM, OsConstants.CAP_BLOCK_SUSPEND ); /* Containers run without some capabilities, so drop any caps that are not available. */ StructCapUserHeader header = new StructCapUserHeader( OsConstants._LINUX_CAPABILITY_VERSION_3, 0); StructCapUserData[] data; try { data = Os.capget(header); } catch (ErrnoException ex) { throw new RuntimeException("Failed to capget()", ex); } capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32); /* Hardcoded command line to start the system server */ // 这是一些写死的参数 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,3005,3006,3007,3009,3010,3011,3012", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT, "com.android.server.SystemServer", }; 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(); Zygote.applyDebuggerSystemProperty(parsedArgs); Zygote.applyInvokeWithSystemProperty(parsedArgs); // 以下都是一些参数的设置 if (Zygote.nativeSupportsMemoryTagging()) { String mode = SystemProperties.get("arm64.memtag.process.system_server", ""); if (mode.isEmpty()) { /* The system server has ASYNC MTE by default, in order to allow * system services to specify their own MTE level later, as you * can't re-enable MTE once it's disabled. */ mode = SystemProperties.get("persist.arm64.memtag.default", "async"); } if (mode.equals("async")) { parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_ASYNC; } else if (mode.equals("sync")) { parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_SYNC; } else if (!mode.equals("off")) { /* When we have an invalid memory tag level, keep the current level. */ parsedArgs.mRuntimeFlags |= Zygote.nativeCurrentTaggingLevel(); Slog.e(TAG, "Unknown memory tag level for the system server: \"" + mode + "\""); } } else if (Zygote.nativeSupportsTaggedPointers()) { /* Enable pointer tagging in the system server. Hardware support for this is present * in all ARMv8 CPUs. */ parsedArgs.mRuntimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI; } /* Enable gwp-asan on the system server with a small probability. This is the same * policy as applied to native processes and system apps. */ parsedArgs.mRuntimeFlags |= Zygote.GWP_ASAN_LEVEL_LOTTERY; if (shouldProfileSystemServer()) { parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER; } // 这里在zygote启动流程中分析过了,最后调用了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 */ // pid == 0时是子进程,也就是新fork出来的SystemServer if (pid == 0) { // 这里没太明白,大概意思就是如果这个设备配置的有另外一个zygote,会返回ture,一般只会有一个吧应该 if (hasSecondZygote(abiList)) { waitForSecondaryZygote(socketName); } // 这里关闭zygoteserver的socket,因为systemserver是fork出来的,默认继承了socket服务,systemserver不需要socket服务 zygoteServer.closeServerSocket(); return handleSystemServerProcess(parsedArgs); } return null; }
handleSystemServerProcess
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) { // set umask to 0077 so new files and directories will default to owner-only permissions. Os.umask(S_IRWXG | S_IRWXO); if (parsedArgs.mNiceName != null) { Process.setArgV0(parsedArgs.mNiceName); } // 这里是获取一下系统环境:可以通过 // emulator_x86_64:/ # env | grep "SYSTEMSERVERCLASSPATH" 结果如下: // SYSTEMSERVERCLASSPATH=/system/framework/com.android.location.provider.jar:/system/framework/services.jar:/apex/com.android.adservices/javalib/service-adservices.jar:/apex/com.android.adservices/javalib/service-sdksandbox.jar:/apex/com.android.appsearch/javalib/service-appsearch.jar:/apex/com.android.art/javalib/service-art.jar:/apex/com.android.media/javalib/service-media-s.jar:/apex/com.android.permission/javalib/service-permission.jar final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH"); if (systemServerClasspath != null) { // 所以这里是能进去的 // Capturing profiles is only supported for debug or eng builds since selinux normally // prevents it. if (shouldProfileSystemServer() && (Build.IS_USERDEBUG || Build.IS_ENG)) { try { // 好像没做什么很重要的事 Log.d(TAG, "Preparing system server profile"); prepareSystemServerProfile(systemServerClasspath); } catch (Exception e) { Log.wtf(TAG, "Failed to set up system server profile", e); } } } // 这里应该是为null的,如果不为null,则会抛出异常,也可以回去看看参数解析的时候这个参数有没有被赋值 /** * else if (arg.equals("--invoke-with")) { // 启动参数里没有这个参数,所以,这里一定是null if (mInvokeWith != null) { throw new IllegalArgumentException( "Duplicate arg specified"); } try { ++curArg; mInvokeWith = args.nextArg(); } catch (IndexOutOfBoundsException ex) { throw new IllegalArgumentException( "--invoke-with requires argument"); } } */ if (parsedArgs.mInvokeWith != null) { String[] args = parsedArgs.mRemainingArgs; // If we have a non-null system server class path, we'll have to duplicate the // existing arguments and append the classpath to it. ART will handle the classpath // correctly when we exec a new process. if (systemServerClasspath != null) { String[] amendedArgs = new String[args.length + 2]; amendedArgs[0] = "-cp"; amendedArgs[1] = systemServerClasspath; System.arraycopy(args, 0, amendedArgs, 2, args.length); args = amendedArgs; } WrapperInit.execApplication(parsedArgs.mInvokeWith, parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion, VMRuntime.getCurrentInstructionSet(), null, args); throw new IllegalStateException("Unexpected return from WrapperInit.execApplication"); } else { // 创建类加载器 ClassLoader cl = getOrCreateSystemServerClassLoader(); if (cl != null) { Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ // 将剩余的参数传递给SystemServer,就是上面解析后的没用到的 // mTargetSdkVersion = VMRuntime.SDK_VERSION_CUR_DEVELOPMENT /** * mDisabledCompatChanges = new long[length]; * for (int i = 0; i < length; i++) { * mDisabledCompatChanges[i] = Long.parseLong(params[i]); * } */ // mRemainingArgs = com.android.server.SystemServer return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mDisabledCompatChanges, parsedArgs.mRemainingArgs, cl); } /* should never reach here */ }
//getOrCreateSystemServerClassLoader
// 这里先知道创建了一个类加载器就行,里面比较复杂,暂时先不看
private static ClassLoader getOrCreateSystemServerClassLoader() {
if (sCachedSystemServerClassLoader == null) {
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
sCachedSystemServerClassLoader = createPathClassLoader(systemServerClasspath,
VMRuntime.SDK_VERSION_CUR_DEVELOPMENT);
}
}
return sCachedSystemServerClassLoader;
}
// ZygoteInit.zygoteInit
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"); // 暂时不分析,log相关 RuntimeInit.redirectLogStreams(); // 也暂时不分析,一些通用的初始化 RuntimeInit.commonInit(); // ZygoteInit这里分析一下 ZygoteInit.nativeZygoteInit(); return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader); }
// nativeZygoteInit
路径: framework/base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
// 这里在AndroidRuntime中是一个虚方法,所以要去子类中找到这个方法的实现
gCurRuntime->onZygoteInit();
}
// gCurRuntime->onZygoteInit()
路径: framework/base/cmds/app_process/app_main.cpp
// 好像就开启了一个线程池,也没干啥子
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
我们继续往回看
//RuntimeInit.applicationInit
RuntimeInit.java
路径: frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader) { // If the application calls System.exit(), terminate the process // immediately without running any shutdown hooks. It is not possible to // shutdown an Android application gracefully. Among other things, the // Android runtime shutdown hooks close the Binder driver, which can cause // leftover running threads to crash before the process actually exits. nativeSetExitWithoutCleanup(true); VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges); // 注意这个argv,是上面传进来的,我们可以原路返回看看它是什么:com.android.server.SystemServer,这里会调用多次,针对systemserver来说,这里是com.android.server.SystemServer final Arguments args = new Arguments(argv); // The end of of the RuntimeInit event (see #zygoteInit). Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); // Remaining arguments are passed to the start class's static main // 查找 这个类的main方法 return findStaticMain(args.startClass, args.startArgs, classLoader); }
// findStaticMain
路径:frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) { Class<?> cl; try { // 通过反射获取类 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 exception's run() method. This arrangement * clears up all the stack frames that were required in setting * up the process. */ // 这里new了一个对象直接返回了,这个东西是一个Runnable,这也是最前面fork后返回的一个runnable,然后执行了run方法 return new MethodAndArgsCaller(m, argv); }
// MethodAndArgsCaller
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 { 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); } } }
我们继续到fork之后的地方
// TODO 这里,startSystemServer为ture,进入if条件中
if (startSystemServer) {
// 创建systemServer进程并启动它
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
if (r != null) {
// 这里调用了run,也就是上面的run,接下来我们需要去看com.android.server.SystemServer的main方法
r.run();
return;
}
}
// com.android.server.SystemServer
路径:frameworks/base/service/java/com/android/server/SystemServer.java
public static void main(String[] args) {
// 直接new了一个SystemServer然后调用了run
new SystemServer().run();
}
// 构造方法,好像没啥重点 public SystemServer() { // Check for factory test mode. mFactoryTestMode = FactoryTest.getMode(); // Record process start information. // Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots; // one for the password screen, second for the actual boot. mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1; mRuntimeStartElapsedTime = SystemClock.elapsedRealtime(); mRuntimeStartUptime = SystemClock.uptimeMillis(); Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime, mRuntimeStartElapsedTime, mRuntimeStartUptime); // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot // We don't use "mStartCount > 1" here because it'll be wrong on a FDE device. // TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before // sys.boot_completed is set. Fix it. mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed")); }
// 重点看一下run方法
private void run() { TimingsTraceAndSlog t = new TimingsTraceAndSlog(); try { // 省略一部分不太重要的代码... // Increase the number of binder threads in system_server // 设置binder的最大线程数,31个,比普通的binder要多不少 BinderInternal.setMaxThreads(sMaxBinderThreads); // Prepare the main looper thread (this thread). android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); // 创建了一个main looper,用来接收handler消息 Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); SystemServiceRegistry.sEnableServiceNotFoundWtf = true; // Initialize native services. 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. // 创建一个context,是从ActivityThread中获取的 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. // 创建一个SystemServiceManager mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); mDumper.addDumpable(mSystemServiceManager); // 将SystemService添加到LocalService中 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. // 重点,启动系统service,根据依赖关系启动 try { t.traceBegin("StartServices"); startBootstrapServices(t); startCoreServices(t); startOtherServices(t); startApexServices(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循环,开始接收消息 Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
整体流程到此为止,我们再看一下最重要的部分,服务启动, 以startBootstrapervices()为例
startBootstrapServices
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) { t.traceBegin("StartWatchdog"); // 启动看门狗 final Watchdog watchdog = Watchdog.getInstance(); watchdog.start(); mDumper.addDumpable(watchdog); t.traceEnd(); // ... 省略若干服务,我们以AMS为例 // Activity manager runs the show. t.traceBegin("StartActivityManager"); // TODO: Might need to move after migration to WM. ActivityTaskManagerService atm = mSystemServiceManager.startService( ActivityTaskManagerService.Lifecycle.class).getService(); // 以AMS为例 mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); t.traceEnd(); // Set up the Application instance for the system process and get started. // 这里将Activity添加到SystemSerer中 t.traceBegin("SetSystemProcess"); mActivityManagerService.setSystemProcess(); t.traceEnd(); // ... 省略若干服务,我们以AMS为例 t.traceBegin("StartDomainVerificationService"); DomainVerificationService domainVerificationService = new DomainVerificationService( mSystemContext, SystemConfig.getInstance(), platformCompat); mSystemServiceManager.startService(domainVerificationService); t.traceEnd(); if (!mOnlyCore) { boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false); if (!disableOtaDexopt) { t.traceBegin("StartOtaDexOptService"); try { Watchdog.getInstance().pauseWatchingCurrentThread("moveab"); OtaDexoptService.main(mSystemContext, mPackageManagerService); } catch (Throwable e) { reportWtf("starting OtaDexOptService", e); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("moveab"); t.traceEnd(); } } } }
ActivityManagerService.Lifecycle.startService
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
// 调用了SystemServiceManager的startService方法
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
// startService
路径:frameworks/base/services/core/java/android/com/android/server/SystemServiceManager.java
public <T extends SystemService> T startService(Class<T> serviceClass) { try { final String name = serviceClass.getName(); Slog.i(TAG, "Starting " + name); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name); // 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); } catch (InstantiationException ex) { throw new RuntimeException("Failed to create service " + name + ": service could not be instantiated", ex); } catch (IllegalAccessException ex) { throw new RuntimeException("Failed to create service " + name + ": service must have a public constructor with a Context argument", ex); } catch (NoSuchMethodException ex) { throw new RuntimeException("Failed to create service " + name + ": service must have a public constructor with a Context argument", ex); } catch (InvocationTargetException ex) { throw new RuntimeException("Failed to create service " + name + ": service constructor threw an exception", ex); } // 启动服务 startService(service); return service; } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } }
// startService
public void startService(@NonNull final SystemService service) { // Check if already started String className = service.getClass().getName(); if (mServiceClassnames.contains(className)) { Slog.i(TAG, "Not starting an already started service " + className); return; } mServiceClassnames.add(className); // Register it. // 给service添加到本地的一个list中了,大概是为了生命周期 mServices.add(service); // Start it. long time = SystemClock.elapsedRealtime(); try { // 调用服务的onStart方法 service.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"); }
// onStart,这里是调用了AMS中的onStart
@Override
public void onStart() {
// 调用了AMS的start方法
mService.start();
}
// start
// 好像没啥很重要的
private void start() {
mBatteryStatsService.publish();
mAppOpsService.publish();
mProcessStats.publish();
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, mInternal);
LocalManagerRegistry.addManager(ActivityManagerLocal.class,
(ActivityManagerLocal) mInternal);
mActivityTaskManager.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
mAppProfiler.onActivityManagerInternalAdded();
CriticalEventLog.init();
}
// 回到启动service的地方
// 这里将systemServiceManager设置到AMS中
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
// 另外,我们前面有一个地方,调用了setSystemProcess,是将AMS添加到ServiceManager中的
public void setSystemProcess() { try { // 添加service到ServiceManager中 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_HIGH); ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); ServiceManager.addService("dbinfo", new DbBinder(this)); mAppProfiler.setCpuInfoService(); ServiceManager.addService("permission", new PermissionController(this)); ServiceManager.addService("processinfo", new ProcessInfoService(this)); ServiceManager.addService("cacheinfo", new CacheBinder(this)); ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); synchronized (this) { ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, false, 0, false, 0, null, new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM)); app.setPersistent(true); app.setPid(MY_PID); app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ); app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM); addPidLocked(app); updateLruProcessLocked(app, false, null); updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException( "Unable to find android system package", e); } // Start watching app ops after we and the package manager are up and running. mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null, new IAppOpsCallback.Stub() { @Override public void opChanged(int op, int uid, String packageName) { if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) { if (getAppOpsManager().checkOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) { runInBackgroundDisabled(uid); } } } }); final int[] cameraOp = {AppOpsManager.OP_CAMERA}; mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() { @Override public void opActiveChanged(int op, int uid, String packageName, String attributionTag, boolean active, @AttributionFlags int attributionFlags, int attributionChainId) { cameraActiveChanged(uid, active); } }); }
到此为止,整个systemserver的启动流程分析完成。
SystemServer 被fork出来之后做了主要的几件事情:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。