Android P ActivityManagerService(二) 初始化

系统服务器的初始化都在SystemServer;就从SystemServer的main方法开始;

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

简单明了的调用了内部run方法;run看着像启动线程,然而这里是直接的方法调用;

private void run() {
    //...
    // Initialize the system context.
        createSystemContext();

        // Create the system service manager.
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // Prepare the thread pool for init tasks that can be parallelized
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }

    /// M: Set paramters to mtkSystemserver.
    sMtkSystemServerIns.setPrameters(BOOT_TIMINGS_TRACE_LOG, mSystemServiceManager,
        mSystemContext);
    // Start services.
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        /// M: For mtk systemserver
        sMtkSystemServerIns.startMtkBootstrapServices();
        startCoreServices();
        /// M: for mtk other service.
        sMtkSystemServerIns.startMtkCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }
    //...
}

AMS的启动在startBootstrapServices中;

首先,通过内部类Lifecycle完成初始化;顺便还帮助PowerManagerService完成了初始化;

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

// 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).
traceBeginAndSlog("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();

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

然后,等大家初始化差不多之后,设置SystemProcess;

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

这里会把AMS加入到ServiceManager;当然顺便还把很多服务加了进去;

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));
        if (MONITOR_CPU_USAGE) {
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        ServiceManager.addService("permission", new PermissionController(this));
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        /// M: ANR Debug Mechanism
        mAnrManager.AddAnrManagerService();
        /// M: DuraSpeed
        mAmsExt.addDuraSpeedService();

        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();
        }

        /// M: Dynamically enable AMS logs @{
        mAmsExt.enableAmsLog(mLruProcesses);
        /// @}

    } 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 (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });
}

startCoreServices中也会有一些AMS相关的动作;setUsageStatsManager;

/**
 * Starts some essential services that are not tangled up in the bootstrap process.
 */
private void startCoreServices() {
    traceBeginAndSlog("StartBatteryService");
    // Tracks the battery level.  Requires LightService.
    mSystemServiceManager.startService(BatteryService.class);
    traceEnd();

    // Tracks application usage stats.
    traceBeginAndSlog("StartUsageService");
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    traceEnd();

    // Tracks whether the updatable WebView is in a ready state and watches for update installs.
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        traceBeginAndSlog("StartWebViewUpdateService");
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
        traceEnd();
    }

    // Tracks cpu time spent in binder calls
    traceBeginAndSlog("StartBinderCallsStatsService");
    BinderCallsStatsService.start();
    traceEnd();
}

同样的,startOtherServices中涉及到一些;

包括:

  • mActivityManagerService.installSystemProviders();
  • watchdog.init(context, mActivityManagerService);
  •  mActivityManagerService.setWindowManager(wm);
  • networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
                        networkManagement);
  • mActivityManagerService.enterSafeMode();
  • mActivityManagerService.showSafeModeOverlay();
  • mActivityManagerService.systemReady
  • mActivityManagerService.startObservingNativeCrashes();
/**
 * Starts a miscellaneous grab bag of stuff that has yet to be refactored
 * and organized.
 */
private void startOtherServices() {
    //...

    try {
        //...

        traceBeginAndSlog("InstallSystemProviders");
        mActivityManagerService.installSystemProviders();
        // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
        SQLiteCompatibilityWalFlags.reset();
        traceEnd();

        //...

        traceBeginAndSlog("InitWatchdog");
        final Watchdog watchdog = Watchdog.getInstance();
        watchdog.init(context, mActivityManagerService);
        traceEnd();

        //...

        traceBeginAndSlog("StartWindowManagerService");
        // WMS needs sensor service ready
        ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
        mSensorServiceStart = null;
        wm = WindowManagerService.main(context, inputManager,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
                !mFirstBoot, mOnlyCore, new PhoneWindowManager());
        ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
        ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
                /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        traceEnd();

        traceBeginAndSlog("SetWindowManagerService");
        mActivityManagerService.setWindowManager(wm);
        traceEnd();

        //...

        traceBeginAndSlog("StartNetworkPolicyManagerService");
        try {
            networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
                    networkManagement);
            ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
        } catch (Throwable e) {
            reportWtf("starting NetworkPolicy Service", e);
        }
        traceEnd();

        //...
    } catch (RuntimeException e) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting core service", e);
    }
    
    //...
    
    // Before things start rolling, be sure we have decided whether
    // we are in safe mode.
    final boolean safeMode = wm.detectSafeMode();
    if (safeMode) {
        traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
        mActivityManagerService.enterSafeMode();
        // Disable the JIT for the system_server process
        VMRuntime.getRuntime().disableJitCompilation();
        traceEnd();
    } else {
        // Enable the JIT for the system_server process
        traceBeginAndSlog("StartJitCompilation");
        VMRuntime.getRuntime().startJitCompilation();
        traceEnd();
    }

    //...

    if (safeMode) {
        mActivityManagerService.showSafeModeOverlay();
    }

    //...

    traceBeginAndSlog("MakePowerManagerServiceReady");
    try {
        // TODO: use boot phase
        mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
    } catch (Throwable e) {
        reportWtf("making Power Manager Service ready", e);
    }
    traceEnd();

    //...

    // We now tell the activity manager it is okay to run third party
    // code.  It will call back into us once it has gotten to the state
    // where third party code can really run (but before it has actually
    // started launching the initial applications), for us to complete our
    // initialization.
    mActivityManagerService.systemReady(() -> {
        Slog.i(TAG, "Making services ready");
        traceBeginAndSlog("StartActivityManagerReadyPhase");
        mSystemServiceManager.startBootPhase(
                SystemService.PHASE_ACTIVITY_MANAGER_READY);
        traceEnd();
        traceBeginAndSlog("StartObservingNativeCrashes");
        try {
            mActivityManagerService.startObservingNativeCrashes();
        } catch (Throwable e) {
            reportWtf("observing native crashes", e);
        }
        traceEnd();

        //...
    }, BOOT_TIMINGS_TRACE_LOG);
}

先,看一眼installSystemProviders,安装系统级的Provider;

public final void installSystemProviders() {
    List<ProviderInfo> providers;
    synchronized (this) {
        ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
        providers = generateApplicationProvidersLocked(app);
        if (providers != null) {
            for (int i=providers.size()-1; i>=0; i--) {
                ProviderInfo pi = (ProviderInfo)providers.get(i);
                if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
                    Slog.w(TAG, "Not installing system proc provider " + pi.name
                            + ": not system .apk");
                    providers.remove(i);
                }
            }
        }
    }
    if (providers != null) {
        mSystemThread.installSystemProviders(providers);
    }

    synchronized (this) {
        mSystemProvidersInstalled = true;
    }

    mConstants.start(mContext.getContentResolver());
    mCoreSettingsObserver = new CoreSettingsObserver(this);
    mFontScaleSettingObserver = new FontScaleSettingObserver();
    mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
    GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());

    // Now that the settings provider is published we can consider sending
    // in a rescue party.
    RescueParty.onSettingsProviderPublished(mContext);

    //mUsageStatsService.monitorPackages();
}

经过层层筛选后,使用通过ActivityThread的installSystemProviders方法进行安装;

public final void installSystemProviders(List<ProviderInfo> providers) {
    if (providers != null) {
        installContentProviders(mInitialApplication, providers);
    }
}

而,installSystemProviders又只是installContentProviders的一个封装罢了;

private void installContentProviders(
        Context context, List<ProviderInfo> providers) {
    final ArrayList<ContentProviderHolder> results = new ArrayList<>();

    for (ProviderInfo cpi : providers) {
        if (DEBUG_PROVIDER) {
            StringBuilder buf = new StringBuilder(128);
            buf.append("Pub ");
            buf.append(cpi.authority);
            buf.append(": ");
            buf.append(cpi.name);
            Log.i(TAG, buf.toString());
        }
        ContentProviderHolder cph = installProvider(context, null, cpi,
                false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
        if (cph != null) {
            cph.noReleaseNeeded = true;
            results.add(cph);
        }
    }

    try {
        ActivityManager.getService().publishContentProviders(
            getApplicationThread(), results);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

之后的安装细节暂不深究;

再,看一眼systemReady;

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) 

这是一个比较乏味的方法,判断到是ready之后,会把传入的runnable给run起来;

不过它还做了一件比较有意思的事情,那就是startHomeActivityLocked;

也是就说,在AMS的systemReady之后,Launcher会被启动;

小结

SystemServer启动服务的三部曲;

  • startBootstrapServices 启动小部分关键的基本服务
  • startCoreServices 启动关键核心服务,PS:除了那小部分之外的关键服务
  • startOtherServices  好吧,上面两个都是关键;

AMS在这三部分中都有涉及;

阶段 行为
startBootstrapServices 初始化启动自己,顺便帮朋友;
startCoreServices 帮朋友;
startOtherServices  帮朋友;初始化系统级provider;SystemReady;启动Launcher(在SystemReady中);

猜你喜欢

转载自blog.csdn.net/weixin_39821531/article/details/89351970