深入理解AMS --- 一 AMS 的啟動
深入理解AMS --- 一 AMS 的啟動
程式碼分支:android-9.0.0_r9
combo: aosp_x86_64-eng
一 Zygote fork
Zygote fork SystemServer 的過程如下:
- ZygoteInit#forkSystemServer
- ZygoteInit#handleSystemServerProcess
- ZygoteInit#zygoteInit
- RuntimeInit#applicationInit
- RuntimeInit#findStaticMain
1.1 Zygote fork SystemServer 程序
ZygoteInit#forkSystemServer 配置system_server 的引數,uid gid 程序顯示的名字等,然後呼叫native 的fork, 在子程序中呼叫handleSystemServerProcess
ZygoteInit.java private static Runnable forkSystemServer(String abiList, String socketName, ZygoteServer zygoteServer) { /* 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,3006,3007,3009,3010", "--capabilities=" + capabilities + "," + capabilities, "--nice-name=system_server", "--runtime-args", "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT, "com.android.server.SystemServer", }; try { /* Request to fork the system server process */ pid = Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.runtimeFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } 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; }
1.2 System_service 程序啟動,準備載入的ClassLoader
ZygoteInit.java private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) { // set umask to 0077 so new files and directories will default to owner-only permissions. if (parsedArgs.invokeWith != null) { } else { ClassLoader cl = null; if (systemServerClasspath != null) { cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion); Thread.currentThread().setContextClassLoader(cl); } /* * Pass the remaining arguments to SystemServer. */ return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); } /* should never reach here */ }
1.3 RuntimeInit 初始化,進一步的準備初始化的環境
ZygoteInit.java public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { RuntimeInit.commonInit(); ZygoteInit.nativeZygoteInit(); return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); }
1.4 通過findStaticMain 方法反射呼叫System_Server 的main 方法。
RuntimeInit.java protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { // Remaining arguments are passed to the start class's static main return findStaticMain(args.startClass, args.startArgs, classLoader); }
二 SystemServer程序
2.1 SystemServer 啟動,然後執行 run 方法。
SystemServer.java public static void main(String[] args) { new SystemServer().run(); } public SystemServer() { // Check for factory test mode. mFactoryTestMode = FactoryTest.getMode(); // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed")); mRuntimeStartElapsedTime = SystemClock.elapsedRealtime(); mRuntimeStartUptime = SystemClock.uptimeMillis(); }
2.2 System_Server 的run 方法
- 開始首先配置 VM 引數
- Binder 引數,
- Loop.prepareMainLooper,
- 建立系統Context createSystemContext
- 啟動系統的各種服務,包括AMS。startBootstrapServices() startCoreServices() startOtherServices()
- Looper.Loop();
private void run() { try { ...... // the property. http://b/11463182 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // Mmmmmm... more memory! VMRuntime.getRuntime().clearGrowthLimit(); // The system server has to run all of the time, so it needs to be // as efficient as possible with its memory usage. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); ...... // Ensure binder calls into the system always run at foreground priority. BinderInternal.disableBackgroundScheduling(true); // Increase the number of binder threads in system_server 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); Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // Initialize native services. System.loadLibrary("android_servers"); // Initialize the system context. createSystemContext(); } finally { } // Start services. try { traceBeginAndSlog("StartServices"); startBootstrapServices(); startCoreServices(); startOtherServices(); SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { } finally { traceEnd(); } StrictMode.initVmDefaults(null); // Loop forever. Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
三 AMS 執行
- SystemServer#startBootstrapServices 通過mSystemServiceManager 啟動ActivityManagerService。
- 啟動ActivityManagerService
3.1 mSystemServiceManager.startService
private void startBootstrapServices() { // Activity manager runs the show. mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setSystemProcess();
3.2 啟動ActivityManagerService
ActivityManagerService 準備工作執行緒,
準備Android 四大元件相關的資料結構,
public ActivityManagerService(Context systemContext) mContext = systemCotex mSystemThread = ActivityThread.currentActivityThread(); mUiContext = mSystemThread.getSystemUiContext(); mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); mHandlerThread.start(); mHandler = new MainHandler(mHandlerThread.getLooper()); mUiHandler = mInjector.getUiHandler(this); mFgBroadcastQueue = new BroadcastQueue(this, mHandler, "foreground", BROADCAST_FG_TIMEOUT, false); mBgBroadcastQueue = new BroadcastQueue(this, mHandle "background", BROADCAST_BG_TIMEOUT, true); mBroadcastQueues[0] = mFgBroadcastQueue; mBroadcastQueues[1] = mBgBroadcastQueue; mServices = new ActiveServices(this); mProviderMap = new ProviderMap(this); mStackSupervisor = createStackSupervisor(); mActivityStarter = new ActivityStarter(this, mStackSupervisor); mRecentTasks = new RecentTasks(this, mStackSupervisor); }
3.3 AMS setSystemProcess()
AMS 通過 setSystemProcess 把System_Server 程序加入到AMS 的程序管理中。載入 framework-res.apk
public void setSystemProcess() { try { 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)); ServiceManager.addService("permission", new PermissionController(this)); ServiceManager.addService("processinfo", new ProcessInfoService(this)); ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); synchronized (this) { ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); app.persistent = true; app.pid = MY_PID; app.maxAdj = ProcessList.SYSTEM_ADJ; app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); synchronized (mPidsSelfLocked) { mPidsSelfLocked.put(app.pid, app); } updateLruProcessLocked(app, false, null); updateOomAdjLocked(); } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException( "Unable to find android system package", e); } }
3.4 installSystemProviders
在中startOtherServices 安裝 SettingProvider
mActivityManagerService.installSystemProviders();
3.5 setWindowManager
mActivityManagerService.setWindowManager(wm);
3.6 systemReady
各種服務啟動完畢後,systemReady. 在systemReady 中先啟動SystemUI, 然後啟動Launcher.

5bdb1821e4b0e4521336b4f6.png