AMS服务的启动

简单说一下systemserver的startservice方法,代码在systemserver的startservcie中

1.通过string名字找到对应的class

2.通过class反射找到constructor,然后newinstance。创建实例

3.创建了实例之后再通过调用实例的onstart方法

1.systemserver.startbootstrapservice

553    private void startBootstrapServices() {
574        traceBeginAndSlog("StartActivityManager");
575        mActivityManagerService = mSystemServiceManager.startService(
576                ActivityManagerService.Lifecycle.class).getService();
577        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
578        mActivityManagerService.setInstaller(installer);
579        traceEnd();
591        traceBeginAndSlog("InitPowerManagement");
592        mActivityManagerService.initPowerManagement();
593        traceEnd();
695        traceBeginAndSlog("SetSystemProcess");
696        mActivityManagerService.setSystemProcess();
697        traceEnd();

####2.lifecycle

2938    public static final class Lifecycle extends SystemService {
2939        private final ActivityManagerService mService;
2940
2941        public Lifecycle(Context context) {
2942            super(context);
2943            mService = new ActivityManagerService(context);
2944        }
2945
2946        @Override
2947        public void onStart() {
2948            mService.start();
2949        }
2950
2951        @Override
2952        public void onBootPhase(int phase) {
2953            mService.mBootPhase = phase;
2954            if (phase == PHASE_SYSTEM_SERVICES_READY) {
2955                mService.mBatteryStatsService.systemServicesReady();
2956                mService.mServices.systemServicesReady();
2957            }
2958        }
2959
2960        @Override
2961        public void onCleanupUser(int userId) {
2962            mService.mBatteryStatsService.onCleanupUser(userId);
2963        }
2964
2965        public ActivityManagerService getService() {
2966            return mService;
2967        }
2968    }

简单说就是创建了一个lifecycle的实例,在创建lifecycle的时候,会创建ams的实例。然后在调用lifecycle的onstart方法时,其实调用的是ams的onstart方法。

2.AMS.构造

3121    public ActivityManagerService(Context systemContext) {
3135        mHandlerThread = new ServiceThread(TAG,
3136                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);//线程名字为activitymanager
3137        mHandlerThread.start();
3138        mHandler = new MainHandler(mHandlerThread.getLooper());
3139        mUiHandler = mInjector.getUiHandler(this);//injector是一个内部管理的类,其实就是new了一个uihandler,同时名字是android.ui
    //创建两个queue来接收广播
3156        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
3157                "foreground", BROADCAST_FG_TIMEOUT, false);
3158        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
3159                "background", BROADCAST_BG_TIMEOUT, true);
3160        mBroadcastQueues[0] = mFgBroadcastQueue;
3161        mBroadcastQueues[1] = mBgBroadcastQueue;
3162
3167        File dataDir = Environment.getDataDirectory();
3168        File systemDir = new File(dataDir, "system");
3169        systemDir.mkdirs();//创建data/system/目录
    //创建batterystatsservice
3174        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
3175        mBatteryStatsService.getActiveStatistics().readLocked();
3176        mBatteryStatsService.scheduleWriteToDisk();
    //创建进程统计服务,写在/data/system/procstats
3181        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
3182
    //创建appops.xml用来统计appops服务
3183        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
3184
    //创建uri的一个统计
3185        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
3202        mStackSupervisor = createStackSupervisor();//创建stacksupervisor
    //创建cputracker的线程
3215        mProcessCpuThread = new Thread("CpuTracker") {
3216            @Override
3217            public void run() {
3218                synchronized (mProcessCpuTracker) {
3219                    mProcessCpuInitLatch.countDown();
3220                    mProcessCpuTracker.init();
3221                }
3222                while (true) {
3223                    try {
3224                        try {
3225                            synchronized(this) {
3226                                final long now = SystemClock.uptimeMillis();
3227                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
3228                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
3229                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
3230                                //        + ", write delay=" + nextWriteDelay);
3231                                if (nextWriteDelay < nextCpuDelay) {
3232                                    nextCpuDelay = nextWriteDelay;
3233                                }
3234                                if (nextCpuDelay > 0) {
3235                                    mProcessCpuMutexFree.set(true);
3236                                    this.wait(nextCpuDelay);
3237                                }
3238                            }
3239                        } catch (InterruptedException e) {
3240                        }
3241                        updateCpuStatsNow();
3242                    } catch (Exception e) {
3243                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
3244                    }
3245                }
3246            }
3247        };

3.AMS.start

3289    private void start() {
3290        removeAllProcessGroups();
3291        mProcessCpuThread.start();
3292
3293        mBatteryStatsService.publish();
3294        mAppOpsService.publish(mContext);
3295        Slog.d("AppOps", "AppOpsService published");
3296        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
3297        // Wait for the synchronized block started in mProcessCpuThread,
3298        // so that any other acccess to mProcessCpuTracker from main thread
3299        // will be blocked during mProcessCpuTracker initialization.
3300        try {
3301            mProcessCpuInitLatch.await();
3302        } catch (InterruptedException e) {
3303            Slog.wtf(TAG, "Interrupted wait during start", e);
3304            Thread.currentThread().interrupt();
3305            throw new IllegalStateException("Interrupted wait during start");
3306        }
3307    }

那么ams的启动就算完成了,然后在startbootstrapservice中还有ams.setsystemrocess

4.AMS.setsystemprocess

2794    public void setSystemProcess() {
2795        try {
2796            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2797                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2798            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2799            ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2800                    DUMP_FLAG_PRIORITY_HIGH);
2801            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2802            ServiceManager.addService("dbinfo", new DbBinder(this));
2803            if (MONITOR_CPU_USAGE) {
2804                ServiceManager.addService("cpuinfo", new CpuBinder(this),
2805                        /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2806            }
2807            ServiceManager.addService("permission", new PermissionController(this));
2808            ServiceManager.addService("processinfo", new ProcessInfoService(this));
2809
2810            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2811                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2812            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2813
2814            synchronized (this) {
2815                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2816                app.persistent = true;
2817                app.pid = MY_PID;
2818                app.maxAdj = ProcessList.SYSTEM_ADJ;
2819                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2820                synchronized (mPidsSelfLocked) {
2821                    mPidsSelfLocked.put(app.pid, app);
2822                }
2823                updateLruProcessLocked(app, false, null);
2824                updateOomAdjLocked();
2825            }
2826        } catch (PackageManager.NameNotFoundException e) {
2827            throw new RuntimeException(
2828                    "Unable to find android system package", e);
2829        }
2830
2831        // Start watching app ops after we and the package manager are up and running.
2832        mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2833                new IAppOpsCallback.Stub() {
2834                    @Override public void opChanged(int op, int uid, String packageName) {
2835                        if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2836                            if (mAppOpsService.checkOperation(op, uid, packageName)
2837                                    != AppOpsManager.MODE_ALLOWED) {
2838                                runInBackgroundDisabled(uid);
2839                            }
2840                        }
2841                    }
2842                });
2843    }

同时,在systemserver的startotherservice中,也会有和ams进行互动的地方

5.systemserver.startcoreservices

753    private void startCoreServices() {

760        traceBeginAndSlog("StartUsageService");
761        mSystemServiceManager.startService(UsageStatsService.class);
762        mActivityManagerService.setUsageStatsManager(
763                LocalServices.getService(UsageStatsManagerInternal.class));
764        traceEnd();

777    }

####system.server.startotherservice

783    private void startOtherServices() {
881            traceBeginAndSlog("InstallSystemProviders");
882            mActivityManagerService.installSystemProviders();
883            // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
884            SQLiteCompatibilityWalFlags.reset();
885            traceEnd();
932            traceBeginAndSlog("SetWindowManagerService");
933            mActivityManagerService.setWindowManager(wm);//与wms建立联系
934            traceEnd();
    
    1866        mActivityManagerService.systemReady(() -> {
1867            Slog.i(TAG, "Making services ready");
1868            traceBeginAndSlog("StartActivityManagerReadyPhase");
1869            mSystemServiceManager.startBootPhase(
1870                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
1871            traceEnd();
1872            traceBeginAndSlog("StartObservingNativeCrashes");
1873            try {
1874                mActivityManagerService.startObservingNativeCrashes();
1875            } catch (Throwable e) {
1876                reportWtf("observing native crashes", e);
1877            }
1878            traceEnd();
1879
1880            // No dependency on Webview preparation in system server. But this should
1881            // be completed before allowing 3rd party
1882            final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
1883            Future<?> webviewPrep = null;
1884            if (!mOnlyCore && mWebViewUpdateService != null) {
1885                webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
1886                    Slog.i(TAG, WEBVIEW_PREPARATION);
1887                    TimingsTraceLog traceLog = new TimingsTraceLog(
1888                            SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
1889                    traceLog.traceBegin(WEBVIEW_PREPARATION);
1890                    ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
1891                    mZygotePreload = null;
1892                    mWebViewUpdateService.prepareWebViewInSystemServer();
1893                    traceLog.traceEnd();
1894                }, WEBVIEW_PREPARATION);
1895            }
1896
1897            if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
1898                traceBeginAndSlog("StartCarServiceHelperService");
1899                mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
1900                traceEnd();
1901            }
1902
1903            traceBeginAndSlog("StartSystemUI");
1904            try {
1905                startSystemUi(context, windowManagerF);//启动systemui也就是statusbar
1906            } catch (Throwable e) {
1907                reportWtf("starting System UI", e);
1908            }
1909            traceEnd();
1910            traceBeginAndSlog("MakeNetworkManagementServiceReady");
1911            try {
1912                if (networkManagementF != null) networkManagementF.systemReady();
1913            } catch (Throwable e) {
1914                reportWtf("making Network Managment Service ready", e);
1915            }
1916            CountDownLatch networkPolicyInitReadySignal = null;
1917            if (networkPolicyF != null) {
1918                networkPolicyInitReadySignal = networkPolicyF
1919                        .networkScoreAndNetworkManagementServiceReady();
1920            }
1921            traceEnd();
1922            traceBeginAndSlog("MakeIpSecServiceReady");
1923            try {
1924                if (ipSecServiceF != null) ipSecServiceF.systemReady();
1925            } catch (Throwable e) {
1926                reportWtf("making IpSec Service ready", e);
1927            }
1928            traceEnd();
1929            traceBeginAndSlog("MakeNetworkStatsServiceReady");
1930            try {
1931                if (networkStatsF != null) networkStatsF.systemReady();
1932            } catch (Throwable e) {
1933                reportWtf("making Network Stats Service ready", e);
1934            }
1935            traceEnd();
1936            traceBeginAndSlog("MakeConnectivityServiceReady");
1937            try {
1938                if (connectivityF != null) connectivityF.systemReady();
1939            } catch (Throwable e) {
1940                reportWtf("making Connectivity Service ready", e);
1941            }
1942            traceEnd();
1943            traceBeginAndSlog("MakeNetworkPolicyServiceReady");
1944            try {
1945                if (networkPolicyF != null) {
1946                    networkPolicyF.systemReady(networkPolicyInitReadySignal);
1947                }
1948            } catch (Throwable e) {
1949                reportWtf("making Network Policy Service ready", e);
1950            }
1951            traceEnd();
1952
1953            traceBeginAndSlog("StartWatchdog");
1954            Watchdog.getInstance().start();
1955            traceEnd();
1956
1957            // Wait for all packages to be prepared
1958            mPackageManagerService.waitForAppDataPrepared();
1959
1960            // It is now okay to let the various system services start their
1961            // third party code...
1962            traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
1963            // confirm webview completion before starting 3rd party
1964            if (webviewPrep != null) {
1965                ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
1966            }
1967            mSystemServiceManager.startBootPhase(
1968                    SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
1969            traceEnd();
1970
1971            traceBeginAndSlog("MakeLocationServiceReady");
1972            try {
1973                if (locationF != null) locationF.systemRunning();
1974            } catch (Throwable e) {
1975                reportWtf("Notifying Location Service running", e);
1976            }
1977            traceEnd();
1978            traceBeginAndSlog("MakeCountryDetectionServiceReady");
1979            try {
1980                if (countryDetectorF != null) countryDetectorF.systemRunning();
1981            } catch (Throwable e) {
1982                reportWtf("Notifying CountryDetectorService running", e);
1983            }
1984            traceEnd();
1985            traceBeginAndSlog("MakeNetworkTimeUpdateReady");
1986            try {
1987                if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
1988            } catch (Throwable e) {
1989                reportWtf("Notifying NetworkTimeService running", e);
1990            }
1991            traceEnd();
1992            traceBeginAndSlog("MakeCommonTimeManagementServiceReady");
1993            try {
1994                if (commonTimeMgmtServiceF != null) {
1995                    commonTimeMgmtServiceF.systemRunning();
1996                }
1997            } catch (Throwable e) {
1998                reportWtf("Notifying CommonTimeManagementService running", e);
1999            }
2000            traceEnd();
2001            traceBeginAndSlog("MakeInputManagerServiceReady");
2002            try {
2003                // TODO(BT) Pass parameter to input manager
2004                if (inputManagerF != null) inputManagerF.systemRunning();
2005            } catch (Throwable e) {
2006                reportWtf("Notifying InputManagerService running", e);
2007            }
2008            traceEnd();
2009            traceBeginAndSlog("MakeTelephonyRegistryReady");
2010            try {
2011                if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
2012            } catch (Throwable e) {
2013                reportWtf("Notifying TelephonyRegistry running", e);
2014            }
2015            traceEnd();
2016            traceBeginAndSlog("MakeMediaRouterServiceReady");
2017            try {
2018                if (mediaRouterF != null) mediaRouterF.systemRunning();
2019            } catch (Throwable e) {
2020                reportWtf("Notifying MediaRouterService running", e);
2021            }
2022            traceEnd();
2023            traceBeginAndSlog("MakeMmsServiceReady");
2024            try {
2025                if (mmsServiceF != null) mmsServiceF.systemRunning();
2026            } catch (Throwable e) {
2027                reportWtf("Notifying MmsService running", e);
2028            }
2029            traceEnd();
2030
2031            traceBeginAndSlog("IncidentDaemonReady");
2032            try {
2033                // TODO: Switch from checkService to getService once it's always
2034                // in the build and should reliably be there.
2035                final IIncidentManager incident = IIncidentManager.Stub.asInterface(
2036                        ServiceManager.getService(Context.INCIDENT_SERVICE));
2037                if (incident != null) incident.systemRunning();
2038            } catch (Throwable e) {
2039                reportWtf("Notifying incident daemon running", e);
2040            }
2041            traceEnd();
2042        }, BOOT_TIMINGS_TRACE_LOG);
2043    }

其实就是将这个runnable传给了systemready,AMS的systemready也分为好几个部分

15354    public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    ...
15469        if (goingCallback != null) goingCallback.run();
    ...
15568    }
    

至此,activitymanagerservice算是启动了。

总结一下

1.systemserver启动了ams

2.先是调用了构造函数,然后再进行了start操作

3.然后进行了setsystemprocess

4.最后调用了systemready来通过广播和其他监听者的方式启动了整个系统

>