Android應用進程啟動流程(Zygote進程與SystemServer進程)

應用啟動流程

Android系統(tǒng)是基于Linux的,所以它的所有應用也是基于Linux的Init進程創(chuàng)建出來的,首先Init進程啟動Zygote(受精卵)進程,然后再fork出其他進程(包括SystemServer),最后開啟各種應用進程。也就是流程如下:

Init進程-->Zygote進程-->SystemServer進程-->應用進程

SystemServer進程中啟動系統(tǒng)的各種服務(ActivityManagerService、PackageManagerService、WindowManagerService...)

Zygote進程啟動流程(API 23)

Init進程啟動Zygote進程時會首先來到ZygoteInit類的main方法:

    public static void main(String argv[]) {
        try {
            RuntimeInit.enableDdms();
            // Start profiling the zygote initialization.
            SamplingProfilerIntegration.start();

            boolean startSystemServer = false;
            String socketName = "zygote";
            String abiList = null;
            for (int i = 1; i < argv.length; i++) {
                if ("start-system-server".equals(argv[i])) {
                    startSystemServer = 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]);
                }
            }

            if (abiList == null) {
                throw new RuntimeException("No ABI list supplied.");
            }

            registerZygoteSocket(socketName);
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
                SystemClock.uptimeMillis());
            preload();
            EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

            // Finish profiling the zygote initialization.
            SamplingProfilerIntegration.writeZygoteSnapshot();

            // Do an initial gc to clean up after startup
            gcAndFinalize();

            // Disable tracing so that forked processes do not inherit stale tracing tags from
            // Zygote.
            Trace.setTracingEnabled(false);

            if (startSystemServer) {
                startSystemServer(abiList, socketName);
            }

            Log.i(TAG, "Accepting command socket connections");
            runSelectLoop(abiList);

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }
  • 第一句enableDdms() 打開DDMS(Dalvik Debug Monitor Service虛擬機調(diào)試服務)
  • SamplingProfilerIntegration.start() 開始分析Zygote
  • 一個循環(huán)解析main方法的參數(shù)列表,判斷是否開啟系統(tǒng)服務,獲取ABI列表,socket名稱
  • registerZygoteSocket(socketName) 注冊socket(android間的進程通信是使用Binder,唯獨Zygote和SystemService是使用socket
  • preload() 初始化
    static void preload() {
        Log.d(TAG, "begin preload");
        preloadClasses();
        preloadResources();
        preloadOpenGL();
        preloadSharedLibraries();
        preloadTextResources();
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        Log.d(TAG, "end preload");
    }
  • preloadClasses()初始化相關的類
  • preloadResources()初始化資源
  • preloadOpenGL()初始化OpenGL
  • preloadSharedLibraries()初始化系統(tǒng)的Lib
  • preloadTextResources()初始化文字資源
  • WebViewFactory.prepareWebViewInZygote()初始化webview

然后調(diào)用startSystemServer方法:

    private static boolean startSystemServer(String abiList, String socketName)
            throws MethodAndArgsCaller, RuntimeException {
        long capabilities = posixCapabilitiesAsBits(
            OsConstants.CAP_BLOCK_SUSPEND,
            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_RESOURCE,
            OsConstants.CAP_SYS_TIME,
            OsConstants.CAP_SYS_TTY_CONFIG
        );
        /* 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,1032,3001,3002,3003,3006,3007",
            "--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);
            }

            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

在調(diào)用Zygote.forkSystemServer方法后創(chuàng)建了SystemServer進程

SystemServer進程啟動流程

在Zygote進程fork出了SystemServer進程后,來到SystemServer的main方法:

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }

就只有一句(還有注意下官方的注釋),調(diào)用了run方法(刪了一些無關代碼):

    private void run() {
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }
        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", "");
        }
        SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
        if (SamplingProfilerIntegration.isEnabled()) {
            SamplingProfilerIntegration.start();
            mProfilerSnapshotTimer = new Timer();
            mProfilerSnapshotTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SamplingProfilerIntegration.writeSnapshot("system_server", null);
                }
            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
        }

        VMRuntime.getRuntime().clearGrowthLimit();

        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

        Build.ensureFingerprintProperty();

        Environment.setUserRequired(true);


        BinderInternal.disableBackgroundScheduling(true);


        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();


        System.loadLibrary("android_servers");


        performPendingShutdown();


        createSystemContext();


        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

        // Start services.
        try {
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        }

        if (StrictMode.conditionallyEnableDebugLogging()) {
            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
        }

        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
  • 首先判斷系統(tǒng)的當前時間,如果小于1970.就設置為1970
  • 使用SystemProperties設置系統(tǒng)的語言、虛擬機庫、內(nèi)存。。。
  • 初始化主Looper(返回的Looper為單例
  • 調(diào)用createSystemContext()創(chuàng)建上下文(activityThread.getSystemContext()返回的Context為單例),并且設置了系統(tǒng)主題
    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
    }

關于Context相關的可以傳送《 從getApplicationContext和getApplication再次梳理Android的Application正確用法》

接下來這兩句:

mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

創(chuàng)建了SystemServiceManager并且加到LocalServices(內(nèi)部是個Map)來保存,來到最后:

startBootstrapServices();
startCoreServices();
startOtherServices();
private void startBootstrapServices() {
        // Wait for installd to finish starting up so that it has a chance to
        // create critical directories such as /data/user with the appropriate
        // permissions.  We need this to complete before we initialize other services.
        Installer installer = mSystemServiceManager.startService(Installer.class);

        // Activity manager runs the show.
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);

        // Power manager needs to be started early because other services need it.
        // Native daemons may be watching for it to be registered so it must be ready
        // to handle incoming binder calls immediately (including being able to verify
        // the permissions for those calls).
        mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

        // Now that the power manager has been started, let the activity manager
        // initialize power management features.
        mActivityManagerService.initPowerManagement();

        // Manages LEDs and display backlight so we need it to bring up the display.
        mSystemServiceManager.startService(LightsService.class);

        // Display manager is needed to provide display metrics before package manager
        // starts up.
        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

        // We need the default display before we can initialize the package manager.
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);

        // Only run "core" apps if we're encrypting the device.
        String cryptState = SystemProperties.get("vold.decrypt");
        if (ENCRYPTING_STATE.equals(cryptState)) {
            Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
            mOnlyCore = true;
        } else if (ENCRYPTED_STATE.equals(cryptState)) {
            Slog.w(TAG, "Device encrypted - only parsing core apps");
            mOnlyCore = true;
        }

        // Start the package manager.
        Slog.i(TAG, "Package Manager");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
        mFirstBoot = mPackageManagerService.isFirstBoot();
        mPackageManager = mSystemContext.getPackageManager();

        Slog.i(TAG, "User Service");
        ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());

        // Initialize attribute cache used to cache resources from packages.
        AttributeCache.init(mSystemContext);

        // Set up the Application instance for the system process and get started.
        mActivityManagerService.setSystemProcess();

        // The sensor service needs access to package manager service, app ops
        // service, and permissions service, therefore we start it after them.
        startSensorService();
    }

首先調(diào)用mSystemServiceManager.startService(Installer.class),這個服務是系統(tǒng)的安裝應用服務,需要最先啟動,來看看SystemServiceManager的startService方法:

    public <T extends SystemService> T startService(Class<T> serviceClass) {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + 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);
        }

        // Register it.
        mServices.add(service);

        // Start it.
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + name
                    + ": onStart threw an exception", ex);
        }
        return service;
    }

通過反射創(chuàng)建實例,然后放到mServices數(shù)組中

private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

最后調(diào)用service的onStart方法,剛才我們傳入的是Installer,來到Installer的onStart方法:

private final InstallerConnection mInstaller;
...
public void onStart() {
        Slog.i(TAG, "Waiting for installd to be ready.");
        mInstaller.waitForConnection();
    }

來到InstallerConnection的waitForConnection方法:

    public void waitForConnection() {
        for (;;) {
            if (execute("ping") >= 0) {
                return;
            }
            Slog.w(TAG, "installd not ready");
            SystemClock.sleep(1000);
        }
    }

一個無限循環(huán)通過ping命令連接Zygote進程,連接成功后才開始啟動服務

繼續(xù)看其他服務的啟動:

mActivityManagerService = mSystemServiceManager.startService(
        ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

接下里啟動了ActivityManagerService,這個服務用來管理Android的四大組件(Activity,Service,Broadcast,ContentProvider),來到ActivityManagerService.Lifecycle類:

public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context);
        }

        @Override
        public void onStart() {
            mService.start();
        }

        public ActivityManagerService getService() {
            return mService;
        }
    }

它的onStart調(diào)用了ActivityManagerService的start方法:

    private void start() {
        Process.removeAllProcessGroups();
        mProcessCpuThread.start();

        mBatteryStatsService.publish(mContext);
        mAppOpsService.publish(mContext);
        Slog.d("AppOps", "AppOpsService published");
        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    }

這里面開啟了操作CPU相關的子線程和電池狀態(tài)相關的服務,應用操作相關的AppOpsService,最后添加到SystemService的存儲數(shù)組中,具體的代碼太復雜,就不贅述了

再繼續(xù)看startBootstrapServices方法:

mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

啟動了PowerManagerService,電源管理服務,這個的作用就不多說了吧,來看看PowerManagerService的onStart方法:

    public void onStart() {
        publishBinderService(Context.POWER_SERVICE, new BinderService());
        publishLocalService(PowerManagerInternal.class, new LocalService());

        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
    }

這幾個方法就不詳細看了,繼續(xù)回到startBootstrapServices:

mActivityManagerService.initPowerManagement();

還記得剛才在ActivityManagerService啟動了電池狀態(tài)相關服務么?現(xiàn)在有了電源管理服務,在ActivityManagerService進行一下初始化:

    public void initPowerManagement() {
        mStackSupervisor.initPowerManagement();
        mBatteryStatsService.initPowerManagement();
        mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
        mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
        mVoiceWakeLock.setReferenceCounted(false);
    }

繼續(xù):

        mSystemServiceManager.startService(LightsService.class);

開啟LightsService,閃關燈LED相關的服務,看看onStart方法:

    @Override
    public void onStart() {
        publishLocalService(LightsManager.class, mService);
    }

然后開啟顯示相關的服務DisplayManagerService:

        mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

也是來到DisplayManagerService的onStart方法,沒什么特別之處:

    @Override
    public void onStart() {
        mHandler.sendEmptyMessage(MSG_REGISTER_DEFAULT_DISPLAY_ADAPTER);

        publishBinderService(Context.DISPLAY_SERVICE, new BinderService(),
                true /*allowIsolated*/);
        publishLocalService(DisplayManagerInternal.class, new LocalService());
    }

再回到startBootstrapServices,啟動PackageManagerService:

mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);//設置默認的顯示界面

mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
        mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();

這個的啟動方法有所不同,直接調(diào)用了PackageManagerService.main:

    public static PackageManagerService main(Context context, Installer installer,
            boolean factoryTest, boolean onlyCore) {
        PackageManagerService m = new PackageManagerService(context, installer,
                factoryTest, onlyCore);
        ServiceManager.addService("package", m);
        return m;
    }

通過構(gòu)造方法new出了PackageManagerService

最后在startBootstrapServices方法中啟動UserManagerService和SensorService,用戶管理服務和傳感器服務:

ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
......
startSensorService();//JNI方法

到了這里startBootstrapServices方法就執(zhí)行完了,在SystemServer的run方法中接下來調(diào)用startCoreServices():

    private void startCoreServices() {
        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);

        // Tracks application usage stats.
        mSystemServiceManager.startService(UsageStatsService.class);
        mActivityManagerService.setUsageStatsManager(
                LocalServices.getService(UsageStatsManagerInternal.class));
        // Update after UsageStatsService is available, needed before performBootDexOpt.
        mPackageManagerService.getUsageStatsIfNoPackageUsageInfo();

        // Tracks whether the updatable WebView is in a ready state and watches for update installs.
        mSystemServiceManager.startService(WebViewUpdateService.class);
    }

在這里啟動了一些其他核心服務,流程跟剛才的啟動流程一樣,都是調(diào)用相關服務的onStart方法來啟動,就不細看了,注意這里的BatteryService不同于剛才在ActivityManagerService的BatteryStatsService

最后調(diào)用startOtherServices() 啟動一些其他服務:振動(VibratorService),網(wǎng)絡管理(NetworkManagementService),網(wǎng)絡狀態(tài)(NetworkStatsService),窗口管理(WindowManagerService)。。。。。。
這個方法代碼太長,就不貼過來了

總結(jié)

  1. Zygote進程是所有進程的父進程,它fork出了SystemServer進程
  2. SystemServer進程的main方法中調(diào)用run方法進行初始化
  3. 在run方法中創(chuàng)建了SystemServiceManager,并且依次調(diào)用startBootstrapServices();startCoreServices();startOtherServices(); 開啟系統(tǒng)服務(三類服務:BootstrapServices-->CoreServices-->OtherServices)
  4. 在啟動服務時調(diào)用服務類的onStart方法來初始化

附上系統(tǒng)服務啟動順序:

Installer-->ActivityManagerService-->PowerManagerService-->

ActivityManagerService-->DisplayManagerService-->PackageManagerService-->

UserManagerService-->SensorService-->BatteryService-->

UsageStatsService-->WebViewUpdateService-->OtherServices

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容