searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

探究Android AMS服务的启动

2023-08-21 02:41:25
96
0

AMS(ActivityManagerService)的作用

ActivityManagerService是Android系统的核心服务之一,负责管理和调度应用程序的生命周期、任务栈、进程管理以及系统资源分配等功能。

  1. 生命周期管理:ActivityManagerService负责启动、暂停、恢复、销毁应用程序的活动(Activity),根据用户操作或系统事件来调度活动的状态变化,例如用户进入某个应用程序或按下返回键。

  2. 任务栈管理:ActivityManagerService维护了所有活动任务栈的信息,包括任务栈的顺序、栈内活动的顺序等。它可以通过接口提供给其他组件访问和操作任务栈,例如启动新的活动时决定将其压入哪个任务栈。

  3. 进程管理:ActivityManagerService负责监控应用程序的进程状态,当系统资源不足时,它可以根据一定的策略来终止一些后台进程,释放资源。同时,它还负责将进程和应用程序的活动进行绑定,可以根据进程的状态来判断哪些活动需要重新创建。

  4. 系统资源分配:ActivityManagerService根据应用程序的需求和系统资源的状态,动态地分配各种资源给应用程序,包括内存、CPU、网络等。它可以对应用程序进行优先级排序,从而保证系统资源的合理分配。

  5. 系统事件处理:ActivityManagerService接收并处理系统事件,例如按键事件、屏幕关闭事件等。它可以将此类事件传递给相应的应用程序来响应用户的操作。

总之,ActivityManagerService在Android系统中起着重要的作用,通过对应用程序的生命周期、任务栈、进程管理以及资源分配进行管理和调度,确保系统的稳定性和高效性。

注:本文所分析的代码基于 AOSP android-12.0.0_r3

1、AMS是如何启动的

 
/**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("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.
        t.traceBegin("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        t.traceEnd();
        ...
        t.traceBegin("StartIStatsService");
        startIStatsService();
        t.traceEnd();

        // Start MemtrackProxyService before ActivityManager, so that early calls
        // to Memtrack::getMemory() don't fail.
        t.traceBegin("MemtrackProxyService");
        startMemtrackProxyService();
        t.traceEnd();
        // 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();
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);        
                mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        t.traceEnd();
 

AMS是在SystemServer进程的startBootstrapServices方法中启动。除了AMS,startBootstrapServices方法还启动了如下引导服务:

  1. Installd(native的安装服务)
  2. PowerStatsService电源状态服务
  3. MemtrackProxyService内存跟踪代理服务
  4. PowerManagerService电源管理服务
  5. PackageManagerService包管理服务
  6. 其他引导服务

2、AMS的构造方法都做了什么

首先来看看AMS的构造函数的源码实现。

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        //...
        //创建名为"ActivityManager"的前台线程,并获取mHandler
        mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);     
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        //通过UiThread类,创建名为"android.ui"的线程
        mUiHandler = mInjector.getUiHandler(this);          
        //创建名为"ActivityManager:procStart"的前台线程,并获取mProcStartHandler         
        mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false /* allowIo */);   
        mProcStartHandlerThread.start();
        mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());        
        //初始化进程列表
        mProcessList.init 
        //实例化低内存检查者
        mLowMemDetector=new LowMemDetector(this); 
        //实例化进程回收优先级
        mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);  
        //-----------广播相关初始化---------------//
        final BroadcastConstants foreConstants  
        //前台广播超时时间
        foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
        final BroadcastConstants backConstants  
        //后台广播超时时间
        backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        final BroadcastConstants offloadConstants  
         //卸载广播超时时间?
        offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        //实例化前台、后台和卸载广播队列,注意传入的是ActivityManager服务线程的Handler实例
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,   
                "foreground", foreConstants, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
        mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                "offload", offloadConstants, true);
        //创建广播队列数组
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        mBroadcastQueues[2] = mOffloadBroadcastQueue;
       //-----------Service,Provder和App异常处理的类实例化---------------//
        mServices = new ActiveServices(this);
        mCpHelper = new ContentProviderHelper(this, true);
        mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
        mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);    
        mUidObserverController = new UidObserverController(mUiHandler);  
        //创建/data/system目录
        final File systemDir = SystemServiceManager.ensureSystemDir();
        //---------猜应该是电池状态服务,根据电池状态去调整内存回收的策略-----//
        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,BackgroundThread.get().getHandler());
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);
        mOomAdjProfiler.batteryPowerChanged(mOnBattery);
        //创建进程状态服务
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
        //获取AppOps服务实例,用于控制一些APP行为
        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
        //猜应该是Uri获取有关的一个管理类
        mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
        //实例化用户管理实例,应该和多用户管理有关
        mUserController = new UserController(this);
        //PendingIntent管理器
        mPendingIntentController = new PendingIntentController(mHandlerThread.getLooper(), mUserController, mConstants);
        //Intent防火墙,先这么理解吧
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        //ATM实例初始化
        mActivityTaskManager = atm;
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
        //添加到Watchdog监控
        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
        //更新oomadj状态
        updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
 

AMS的构造方法主要做了:
1、创建 ActivityManager 、android.ui、ActivityManager:procStart 服务线程。
2、设置前台广播、后台广播的超时时间,初始化广播队列和广播数组。
3、初始化 Service, Provider,以及AppErrors。
4、创建/data/system目录,并保存procstats、appops.xml等文件。
5、创建 Intent 防火墙IntentFirewall。
6、Watchdog 实例,并将AMS 添加到看门狗Monitor中。
7、更新 oomadj 状态。

3、AMS.start()方法实现

先来看下AMS的start()方法源码。

    private void start() {
        //清除所有进程组
        removeAllProcessGroups();
        //启动/发布电源状态服务
        mBatteryStatsService.publish();
        //启动/发布AppOps行为管理服务
        mAppOpsService.publish();
        Slog.d("AppOps", "AppOpsService published");
        //添加ActivityManagerInternal这个本地服务到本地服务中
        LocalServices.addService(ActivityManagerInternal.class, mInternal);
        LocalManagerRegistry.addManager(ActivityManagerLocal.class,(ActivityManagerLocal) mInternal);
        mActivityTaskManager.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        mAppProfiler.onActivityManagerInternalAdded();
    }

至此AMS实例创建完并返回,继续SystemServer的startBootstrapServices方法;

4、AMS设置系统进程实现

AMS完成实例化后,在SystemServer的startBootstrapServices方法最后会调用AMS的setSystemProcess方法设置系统进程。这里做了什么呢?

先来看下源码实现:

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        // 启动PKMS
        //...
        // Set up the Application instance for the system process and get started.
        t.traceBegin("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        t.traceEnd();
    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));
            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, new HostingRecord("system"));
                app.setPersistent(true);
                app.setPid(MY_PID);
                app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                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);
        }
    }
 

setSystemProcess方法添加各种服务,包括meminfo、gfxinfo、dbinfo、cpuinfo以及permission和processinfo系统Service。同时更新进程相关的 Lru 算法,以及oom_adj 值。

继续回到SystemServer的startOtherServices方法,这已经是启动系统服务的后段,此时会执行系统ContentProvider的安装工作;

5、安装系统Provider

首先看下源代码。

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
            //....
            t.traceBegin("InstallSystemProviders"); 
            mActivityManagerService.getContentProviderHelper().installSystemProviders();
            // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
            SQLiteCompatibilityWalFlags.reset();
            t.traceEnd();
 

此时调用到ContentProviderHelper.java的installSystemProviders()方法,执行系统Provider的安装。看下实现源码:

   public final void installSystemProviders() {
        List<ProviderInfo> providers;
        synchronized (mService) {
            //安装所有uid=system进程的ContentProvider
            ProcessRecord app = mService.mProcessList
                    .getProcessNamesLOSP().get("system", SYSTEM_UID);
            providers = generateApplicationProvidersLocked(app);
            if (providers != null) {
                for (int i = providers.size() - 1; i >= 0; i--) {
                    ProviderInfo pi = 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) {
            mService.mSystemThread.installSystemProviders(providers);
        }
        synchronized (this) {
            mSystemProvidersInstalled = true;
        }

        mService.mConstants.start(mService.mContext.getContentResolver());
        mService.mCoreSettingsObserver = new CoreSettingsObserver(mService);
        mService.mActivityTaskManager.installSystemProviders();
        new DevelopmentSettingsObserver(); // init to observe developer settings enable/disable
        SettingsToPropertiesMapper.start(mService.mContext.getContentResolver());
        mService.mOomAdjuster.initSettings();

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

6、AMS.systemReady()准备完成

好了,经历了SystemServer的startOtherServices()方法“又长又臭”的一堆实现后,WMS实例也创建了,最后收尾阶段就可以通知AMS做好系统准备,然后拉起我们第一个应用进程了。
首先看下AMS.systemReady()方法实现;

2673        // We now tell the activity manager it is okay to run third party
2674        // code.  It will call back into us once it has gotten to the state
2675        // where third party code can really run (but before it has actually
2676        // started launching the initial applications), for us to complete our
2677        // initialization.
2678        mActivityManagerService.systemReady(() -> {
2679            Slog.i(TAG, "Making services ready");
2680            t.traceBegin("StartActivityManagerReadyPhase");
2681            mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
2682            t.traceEnd();

AMS的systemReady方法源码实现:

 
         /**
7504     * Ready. Set. Go!
7505     */
7506    public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
7507        t.traceBegin("PhaseActivityManagerReady");
7508        mSystemServiceManager.preSystemReady();
7509        synchronized(this) {
7510            if (mSystemReady) {
7511                // If we're done calling all the receivers, run the next "boot phase" passed in
7512                // by the SystemServer
7513                if (goingCallback != null) {
7514                    goingCallback.run();
7515                }
7516                t.traceEnd(); // PhaseActivityManagerReady
7517                return;
7518            }
7519
7520            t.traceBegin("controllersReady");
7521            mLocalDeviceIdleController =
7522                    LocalServices.getService(DeviceIdleInternal.class);
7523            mActivityTaskManager.onSystemReady();
7524            // Make sure we have the current profile info, since it is needed for security checks.
7525            mUserController.onSystemReady();
7526            mAppOpsService.systemReady();
7527            mProcessList.onSystemReady();
7528            mSystemReady = true;
7529            t.traceEnd();
7530        }
7531
7532        try {
7533            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
7534                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
7535                    .getSerial();
7536        } catch (RemoteException e) {}
7537
7538        t.traceBegin("killProcesses");
7539        ArrayList<ProcessRecord> procsToKill = null;
7540        synchronized(mPidsSelfLocked) {
7541            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7542                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7543                if (!isAllowedWhileBooting(proc.info)){
7544                    if (procsToKill == null) {
7545                        procsToKill = new ArrayList<ProcessRecord>();
7546                    }
7547                    procsToKill.add(proc);
7548                }
7549            }
7550        }
7551
7552        synchronized(this) {
7553            if (procsToKill != null) {
7554                for (int i = procsToKill.size() - 1; i >= 0; i--) {
7555                    ProcessRecord proc = procsToKill.get(i);
7556                    Slog.i(TAG, "Removing system update proc: " + proc);
7557                    mProcessList.removeProcessLocked(proc, true, false,
7558                            ApplicationExitInfo.REASON_OTHER,
7559                            ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
7560                            "system update done");
7561                }
7562            }
7563
7564            // Now that we have cleaned up any update processes, we
7565            // are ready to start launching real processes and know that
7566            // we won't trample on them any more.
7567            mProcessesReady = true;
7568        }
7569        t.traceEnd(); // KillProcesses
7570
7571        Slog.i(TAG, "System now ready");
7572
7573        EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
7574
7575        t.traceBegin("updateTopComponentForFactoryTest");
7576        mAtmInternal.updateTopComponentForFactoryTest();
7577        t.traceEnd();
7578
7579        t.traceBegin("registerActivityLaunchObserver");
7580        mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
7581        t.traceEnd();
7582
7583        t.traceBegin("watchDeviceProvisioning");
7584        watchDeviceProvisioning(mContext);
7585        t.traceEnd();
7586
7587        t.traceBegin("retrieveSettings");
7588        retrieveSettings();
7589        t.traceEnd();
7590
7591        t.traceBegin("Ugm.onSystemReady");
7592        mUgmInternal.onSystemReady();
7593        t.traceEnd();
7594
7595        t.traceBegin("updateForceBackgroundCheck");
7596        final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
7597        if (pmi != null) {
7598            pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
7599                    state -> updateForceBackgroundCheck(state.batterySaverEnabled));
7600            updateForceBackgroundCheck(
7601                    pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
7602        } else {
7603            Slog.wtf(TAG, "PowerManagerInternal not found.");
7604        }
7605        t.traceEnd();
7606
7607        if (goingCallback != null) goingCallback.run();
7608
7609        t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
7610        // Check the current user here as a user can be started inside goingCallback.run() from
7611        // other system services.
7612        final int currentUserId = mUserController.getCurrentUserId();
7613        Slog.i(TAG, "Current user:" + currentUserId);
7614        if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
7615            // User other than system user has started. Make sure that system user is already
7616            // started before switching user.
7617            throw new RuntimeException("System user not started while current user is:"
7618                    + currentUserId);
7619        }
7620        t.traceEnd();
7621
7622        t.traceBegin("ActivityManagerStartApps");
7623        mBatteryStatsService.onSystemReady();
7624        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
7625                Integer.toString(currentUserId), currentUserId);
7626        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
7627                Integer.toString(currentUserId), currentUserId);
7628
7629        // On Automotive, at this point the system user has already been started and unlocked,
7630        // and some of the tasks we do here have already been done. So skip those in that case.
7631        // TODO(b/132262830): this workdound shouldn't be necessary once we move the
7632        // headless-user start logic to UserManager-land
7633        final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
7634
7635        if (bootingSystemUser) {
7636            mSystemServiceManager.onUserStarting(t, currentUserId);
7637        }
7638
7639        synchronized (this) {
7640            // Only start up encryption-aware persistent apps; once user is
7641            // unlocked we'll come back around and start unaware apps
7642            t.traceBegin("startPersistentApps");
7643            startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
7644            t.traceEnd();
7645
7646            // Start up initial activity.
7647            mBooting = true;
7648            // Enable home activity for system user, so that the system can always boot. We don't
7649            // do this when the system user is not setup since the setup wizard should be the one
7650            // to handle home activity in this case.
7651            if (UserManager.isSplitSystemUser() &&
7652                    Settings.Secure.getInt(mContext.getContentResolver(),
7653                         Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
7654                    || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
7655                t.traceBegin("enableHomeActivity");
7656                ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
7657                try {
7658                    AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
7659                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
7660                            UserHandle.USER_SYSTEM);
7661                } catch (RemoteException e) {
7662                    throw e.rethrowAsRuntimeException();
7663                }
7664                t.traceEnd();
7665            }
7666
7667            if (bootingSystemUser) {
7668                t.traceBegin("startHomeOnAllDisplays");
                    //启动HOME Activity
7669                mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
7670                t.traceEnd();
7671            }
7672
7673            t.traceBegin("showSystemReadyErrorDialogs");
7674            mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
7675            t.traceEnd();
7676
7677
7678            if (bootingSystemUser) {
7679                t.traceBegin("sendUserStartBroadcast");
7680                final int callingUid = Binder.getCallingUid();
7681                final int callingPid = Binder.getCallingPid();
7682                final long ident = Binder.clearCallingIdentity();
7683                try {
7684                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7685                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7686                            | Intent.FLAG_RECEIVER_FOREGROUND);
7687                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7688                    broadcastIntentLocked(null, null, null, intent,
7689                            null, null, 0, null, null, null, null, OP_NONE,
7690                            null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7691                            currentUserId);
7692                    intent = new Intent(Intent.ACTION_USER_STARTING);
7693                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7694                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7695                    broadcastIntentLocked(null, null, null, intent, null,
7696                            new IIntentReceiver.Stub() {
7697                                @Override
7698                                public void performReceive(Intent intent, int resultCode,
7699                                        String data, Bundle extras, boolean ordered, boolean sticky,
7700                                        int sendingUser) {}
7701                            }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE,
7702                            null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7703                            UserHandle.USER_ALL);
7704                } catch (Throwable e) {
7705                    Slog.wtf(TAG, "Failed sending first user broadcasts", e);
7706                } finally {
7707                    Binder.restoreCallingIdentity(ident);
7708                }
7709                t.traceEnd();
7710            } else {
7711                Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
7712                        + currentUserId);
7713            }
7714
7715            t.traceBegin("resumeTopActivities");
7716            mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
7717            t.traceEnd();
7718
7719            if (bootingSystemUser) {
7720                t.traceBegin("sendUserSwitchBroadcasts");
7721                mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
7722                t.traceEnd();
7723            }
7724
7725            t.traceBegin("setBinderProxies");
7726            BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
7727                    BINDER_PROXY_LOW_WATERMARK);
7728            BinderInternal.nSetBinderProxyCountEnabled(true);
7729            BinderInternal.setBinderProxyCountCallback(
7730                    (uid) -> {
7731                        Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
7732                                + Process.myUid());
7733                        BinderProxy.dumpProxyDebugInfo();
7734                        if (uid == Process.SYSTEM_UID) {
7735                            Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
7736                        } else {
7737                            killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
7738                                    "Too many Binders sent to SYSTEM");
7739                        }
7740                    }, mHandler);
7741            t.traceEnd(); // setBinderProxies
7742
7743            t.traceEnd(); // ActivityManagerStartApps
7744            t.traceEnd(); // PhaseActivityManagerReady
7745        }
7746    }
 

SystemReady 主要做了以下事情:
1、回调几个服务的SystemReady方法,如AppOps;
2、kill 掉非persistent app进程。
3、启动 persistent app。
4、启动Home Activity 如Launcher

总结

总结AMS的启动流程如下图。

0条评论
作者已关闭评论
hi_long
15文章数
0粉丝数
hi_long
15 文章 | 0 粉丝
hi_long
15文章数
0粉丝数
hi_long
15 文章 | 0 粉丝
原创

探究Android AMS服务的启动

2023-08-21 02:41:25
96
0

AMS(ActivityManagerService)的作用

ActivityManagerService是Android系统的核心服务之一,负责管理和调度应用程序的生命周期、任务栈、进程管理以及系统资源分配等功能。

  1. 生命周期管理:ActivityManagerService负责启动、暂停、恢复、销毁应用程序的活动(Activity),根据用户操作或系统事件来调度活动的状态变化,例如用户进入某个应用程序或按下返回键。

  2. 任务栈管理:ActivityManagerService维护了所有活动任务栈的信息,包括任务栈的顺序、栈内活动的顺序等。它可以通过接口提供给其他组件访问和操作任务栈,例如启动新的活动时决定将其压入哪个任务栈。

  3. 进程管理:ActivityManagerService负责监控应用程序的进程状态,当系统资源不足时,它可以根据一定的策略来终止一些后台进程,释放资源。同时,它还负责将进程和应用程序的活动进行绑定,可以根据进程的状态来判断哪些活动需要重新创建。

  4. 系统资源分配:ActivityManagerService根据应用程序的需求和系统资源的状态,动态地分配各种资源给应用程序,包括内存、CPU、网络等。它可以对应用程序进行优先级排序,从而保证系统资源的合理分配。

  5. 系统事件处理:ActivityManagerService接收并处理系统事件,例如按键事件、屏幕关闭事件等。它可以将此类事件传递给相应的应用程序来响应用户的操作。

总之,ActivityManagerService在Android系统中起着重要的作用,通过对应用程序的生命周期、任务栈、进程管理以及资源分配进行管理和调度,确保系统的稳定性和高效性。

注:本文所分析的代码基于 AOSP android-12.0.0_r3

1、AMS是如何启动的

 
/**
     * Starts the small tangle of critical services that are needed to get the system off the
     * ground.  These services have complex mutual dependencies which is why we initialize them all
     * in one place here.  Unless your service is also entwined in these dependencies, it should be
     * initialized in one of the other functions.
     */
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        t.traceBegin("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.
        t.traceBegin("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        t.traceEnd();
        ...
        t.traceBegin("StartIStatsService");
        startIStatsService();
        t.traceEnd();

        // Start MemtrackProxyService before ActivityManager, so that early calls
        // to Memtrack::getMemory() don't fail.
        t.traceBegin("MemtrackProxyService");
        startMemtrackProxyService();
        t.traceEnd();
        // 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();
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);        
                mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        t.traceEnd();
 

AMS是在SystemServer进程的startBootstrapServices方法中启动。除了AMS,startBootstrapServices方法还启动了如下引导服务:

  1. Installd(native的安装服务)
  2. PowerStatsService电源状态服务
  3. MemtrackProxyService内存跟踪代理服务
  4. PowerManagerService电源管理服务
  5. PackageManagerService包管理服务
  6. 其他引导服务

2、AMS的构造方法都做了什么

首先来看看AMS的构造函数的源码实现。

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        //...
        //创建名为"ActivityManager"的前台线程,并获取mHandler
        mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);     
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        //通过UiThread类,创建名为"android.ui"的线程
        mUiHandler = mInjector.getUiHandler(this);          
        //创建名为"ActivityManager:procStart"的前台线程,并获取mProcStartHandler         
        mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false /* allowIo */);   
        mProcStartHandlerThread.start();
        mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());        
        //初始化进程列表
        mProcessList.init 
        //实例化低内存检查者
        mLowMemDetector=new LowMemDetector(this); 
        //实例化进程回收优先级
        mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);  
        //-----------广播相关初始化---------------//
        final BroadcastConstants foreConstants  
        //前台广播超时时间
        foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
        final BroadcastConstants backConstants  
        //后台广播超时时间
        backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        final BroadcastConstants offloadConstants  
         //卸载广播超时时间?
        offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        //实例化前台、后台和卸载广播队列,注意传入的是ActivityManager服务线程的Handler实例
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,   
                "foreground", foreConstants, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
        mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                "offload", offloadConstants, true);
        //创建广播队列数组
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        mBroadcastQueues[2] = mOffloadBroadcastQueue;
       //-----------Service,Provder和App异常处理的类实例化---------------//
        mServices = new ActiveServices(this);
        mCpHelper = new ContentProviderHelper(this, true);
        mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
        mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);    
        mUidObserverController = new UidObserverController(mUiHandler);  
        //创建/data/system目录
        final File systemDir = SystemServiceManager.ensureSystemDir();
        //---------猜应该是电池状态服务,根据电池状态去调整内存回收的策略-----//
        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,BackgroundThread.get().getHandler());
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);
        mOomAdjProfiler.batteryPowerChanged(mOnBattery);
        //创建进程状态服务
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
        //获取AppOps服务实例,用于控制一些APP行为
        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
        //猜应该是Uri获取有关的一个管理类
        mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
        //实例化用户管理实例,应该和多用户管理有关
        mUserController = new UserController(this);
        //PendingIntent管理器
        mPendingIntentController = new PendingIntentController(mHandlerThread.getLooper(), mUserController, mConstants);
        //Intent防火墙,先这么理解吧
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        //ATM实例初始化
        mActivityTaskManager = atm;
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
        //添加到Watchdog监控
        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
        //更新oomadj状态
        updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
 

AMS的构造方法主要做了:
1、创建 ActivityManager 、android.ui、ActivityManager:procStart 服务线程。
2、设置前台广播、后台广播的超时时间,初始化广播队列和广播数组。
3、初始化 Service, Provider,以及AppErrors。
4、创建/data/system目录,并保存procstats、appops.xml等文件。
5、创建 Intent 防火墙IntentFirewall。
6、Watchdog 实例,并将AMS 添加到看门狗Monitor中。
7、更新 oomadj 状态。

3、AMS.start()方法实现

先来看下AMS的start()方法源码。

    private void start() {
        //清除所有进程组
        removeAllProcessGroups();
        //启动/发布电源状态服务
        mBatteryStatsService.publish();
        //启动/发布AppOps行为管理服务
        mAppOpsService.publish();
        Slog.d("AppOps", "AppOpsService published");
        //添加ActivityManagerInternal这个本地服务到本地服务中
        LocalServices.addService(ActivityManagerInternal.class, mInternal);
        LocalManagerRegistry.addManager(ActivityManagerLocal.class,(ActivityManagerLocal) mInternal);
        mActivityTaskManager.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        mAppProfiler.onActivityManagerInternalAdded();
    }

至此AMS实例创建完并返回,继续SystemServer的startBootstrapServices方法;

4、AMS设置系统进程实现

AMS完成实例化后,在SystemServer的startBootstrapServices方法最后会调用AMS的setSystemProcess方法设置系统进程。这里做了什么呢?

先来看下源码实现:

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        // 启动PKMS
        //...
        // Set up the Application instance for the system process and get started.
        t.traceBegin("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        t.traceEnd();
    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));
            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, new HostingRecord("system"));
                app.setPersistent(true);
                app.setPid(MY_PID);
                app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                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);
        }
    }
 

setSystemProcess方法添加各种服务,包括meminfo、gfxinfo、dbinfo、cpuinfo以及permission和processinfo系统Service。同时更新进程相关的 Lru 算法,以及oom_adj 值。

继续回到SystemServer的startOtherServices方法,这已经是启动系统服务的后段,此时会执行系统ContentProvider的安装工作;

5、安装系统Provider

首先看下源代码。

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
            //....
            t.traceBegin("InstallSystemProviders"); 
            mActivityManagerService.getContentProviderHelper().installSystemProviders();
            // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
            SQLiteCompatibilityWalFlags.reset();
            t.traceEnd();
 

此时调用到ContentProviderHelper.java的installSystemProviders()方法,执行系统Provider的安装。看下实现源码:

   public final void installSystemProviders() {
        List<ProviderInfo> providers;
        synchronized (mService) {
            //安装所有uid=system进程的ContentProvider
            ProcessRecord app = mService.mProcessList
                    .getProcessNamesLOSP().get("system", SYSTEM_UID);
            providers = generateApplicationProvidersLocked(app);
            if (providers != null) {
                for (int i = providers.size() - 1; i >= 0; i--) {
                    ProviderInfo pi = 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) {
            mService.mSystemThread.installSystemProviders(providers);
        }
        synchronized (this) {
            mSystemProvidersInstalled = true;
        }

        mService.mConstants.start(mService.mContext.getContentResolver());
        mService.mCoreSettingsObserver = new CoreSettingsObserver(mService);
        mService.mActivityTaskManager.installSystemProviders();
        new DevelopmentSettingsObserver(); // init to observe developer settings enable/disable
        SettingsToPropertiesMapper.start(mService.mContext.getContentResolver());
        mService.mOomAdjuster.initSettings();

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

6、AMS.systemReady()准备完成

好了,经历了SystemServer的startOtherServices()方法“又长又臭”的一堆实现后,WMS实例也创建了,最后收尾阶段就可以通知AMS做好系统准备,然后拉起我们第一个应用进程了。
首先看下AMS.systemReady()方法实现;

2673        // We now tell the activity manager it is okay to run third party
2674        // code.  It will call back into us once it has gotten to the state
2675        // where third party code can really run (but before it has actually
2676        // started launching the initial applications), for us to complete our
2677        // initialization.
2678        mActivityManagerService.systemReady(() -> {
2679            Slog.i(TAG, "Making services ready");
2680            t.traceBegin("StartActivityManagerReadyPhase");
2681            mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
2682            t.traceEnd();

AMS的systemReady方法源码实现:

 
         /**
7504     * Ready. Set. Go!
7505     */
7506    public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
7507        t.traceBegin("PhaseActivityManagerReady");
7508        mSystemServiceManager.preSystemReady();
7509        synchronized(this) {
7510            if (mSystemReady) {
7511                // If we're done calling all the receivers, run the next "boot phase" passed in
7512                // by the SystemServer
7513                if (goingCallback != null) {
7514                    goingCallback.run();
7515                }
7516                t.traceEnd(); // PhaseActivityManagerReady
7517                return;
7518            }
7519
7520            t.traceBegin("controllersReady");
7521            mLocalDeviceIdleController =
7522                    LocalServices.getService(DeviceIdleInternal.class);
7523            mActivityTaskManager.onSystemReady();
7524            // Make sure we have the current profile info, since it is needed for security checks.
7525            mUserController.onSystemReady();
7526            mAppOpsService.systemReady();
7527            mProcessList.onSystemReady();
7528            mSystemReady = true;
7529            t.traceEnd();
7530        }
7531
7532        try {
7533            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
7534                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
7535                    .getSerial();
7536        } catch (RemoteException e) {}
7537
7538        t.traceBegin("killProcesses");
7539        ArrayList<ProcessRecord> procsToKill = null;
7540        synchronized(mPidsSelfLocked) {
7541            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7542                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7543                if (!isAllowedWhileBooting(proc.info)){
7544                    if (procsToKill == null) {
7545                        procsToKill = new ArrayList<ProcessRecord>();
7546                    }
7547                    procsToKill.add(proc);
7548                }
7549            }
7550        }
7551
7552        synchronized(this) {
7553            if (procsToKill != null) {
7554                for (int i = procsToKill.size() - 1; i >= 0; i--) {
7555                    ProcessRecord proc = procsToKill.get(i);
7556                    Slog.i(TAG, "Removing system update proc: " + proc);
7557                    mProcessList.removeProcessLocked(proc, true, false,
7558                            ApplicationExitInfo.REASON_OTHER,
7559                            ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
7560                            "system update done");
7561                }
7562            }
7563
7564            // Now that we have cleaned up any update processes, we
7565            // are ready to start launching real processes and know that
7566            // we won't trample on them any more.
7567            mProcessesReady = true;
7568        }
7569        t.traceEnd(); // KillProcesses
7570
7571        Slog.i(TAG, "System now ready");
7572
7573        EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
7574
7575        t.traceBegin("updateTopComponentForFactoryTest");
7576        mAtmInternal.updateTopComponentForFactoryTest();
7577        t.traceEnd();
7578
7579        t.traceBegin("registerActivityLaunchObserver");
7580        mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
7581        t.traceEnd();
7582
7583        t.traceBegin("watchDeviceProvisioning");
7584        watchDeviceProvisioning(mContext);
7585        t.traceEnd();
7586
7587        t.traceBegin("retrieveSettings");
7588        retrieveSettings();
7589        t.traceEnd();
7590
7591        t.traceBegin("Ugm.onSystemReady");
7592        mUgmInternal.onSystemReady();
7593        t.traceEnd();
7594
7595        t.traceBegin("updateForceBackgroundCheck");
7596        final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
7597        if (pmi != null) {
7598            pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
7599                    state -> updateForceBackgroundCheck(state.batterySaverEnabled));
7600            updateForceBackgroundCheck(
7601                    pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
7602        } else {
7603            Slog.wtf(TAG, "PowerManagerInternal not found.");
7604        }
7605        t.traceEnd();
7606
7607        if (goingCallback != null) goingCallback.run();
7608
7609        t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
7610        // Check the current user here as a user can be started inside goingCallback.run() from
7611        // other system services.
7612        final int currentUserId = mUserController.getCurrentUserId();
7613        Slog.i(TAG, "Current user:" + currentUserId);
7614        if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
7615            // User other than system user has started. Make sure that system user is already
7616            // started before switching user.
7617            throw new RuntimeException("System user not started while current user is:"
7618                    + currentUserId);
7619        }
7620        t.traceEnd();
7621
7622        t.traceBegin("ActivityManagerStartApps");
7623        mBatteryStatsService.onSystemReady();
7624        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
7625                Integer.toString(currentUserId), currentUserId);
7626        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
7627                Integer.toString(currentUserId), currentUserId);
7628
7629        // On Automotive, at this point the system user has already been started and unlocked,
7630        // and some of the tasks we do here have already been done. So skip those in that case.
7631        // TODO(b/132262830): this workdound shouldn't be necessary once we move the
7632        // headless-user start logic to UserManager-land
7633        final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
7634
7635        if (bootingSystemUser) {
7636            mSystemServiceManager.onUserStarting(t, currentUserId);
7637        }
7638
7639        synchronized (this) {
7640            // Only start up encryption-aware persistent apps; once user is
7641            // unlocked we'll come back around and start unaware apps
7642            t.traceBegin("startPersistentApps");
7643            startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
7644            t.traceEnd();
7645
7646            // Start up initial activity.
7647            mBooting = true;
7648            // Enable home activity for system user, so that the system can always boot. We don't
7649            // do this when the system user is not setup since the setup wizard should be the one
7650            // to handle home activity in this case.
7651            if (UserManager.isSplitSystemUser() &&
7652                    Settings.Secure.getInt(mContext.getContentResolver(),
7653                         Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
7654                    || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
7655                t.traceBegin("enableHomeActivity");
7656                ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
7657                try {
7658                    AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
7659                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
7660                            UserHandle.USER_SYSTEM);
7661                } catch (RemoteException e) {
7662                    throw e.rethrowAsRuntimeException();
7663                }
7664                t.traceEnd();
7665            }
7666
7667            if (bootingSystemUser) {
7668                t.traceBegin("startHomeOnAllDisplays");
                    //启动HOME Activity
7669                mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
7670                t.traceEnd();
7671            }
7672
7673            t.traceBegin("showSystemReadyErrorDialogs");
7674            mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
7675            t.traceEnd();
7676
7677
7678            if (bootingSystemUser) {
7679                t.traceBegin("sendUserStartBroadcast");
7680                final int callingUid = Binder.getCallingUid();
7681                final int callingPid = Binder.getCallingPid();
7682                final long ident = Binder.clearCallingIdentity();
7683                try {
7684                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7685                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7686                            | Intent.FLAG_RECEIVER_FOREGROUND);
7687                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7688                    broadcastIntentLocked(null, null, null, intent,
7689                            null, null, 0, null, null, null, null, OP_NONE,
7690                            null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7691                            currentUserId);
7692                    intent = new Intent(Intent.ACTION_USER_STARTING);
7693                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7694                    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7695                    broadcastIntentLocked(null, null, null, intent, null,
7696                            new IIntentReceiver.Stub() {
7697                                @Override
7698                                public void performReceive(Intent intent, int resultCode,
7699                                        String data, Bundle extras, boolean ordered, boolean sticky,
7700                                        int sendingUser) {}
7701                            }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE,
7702                            null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7703                            UserHandle.USER_ALL);
7704                } catch (Throwable e) {
7705                    Slog.wtf(TAG, "Failed sending first user broadcasts", e);
7706                } finally {
7707                    Binder.restoreCallingIdentity(ident);
7708                }
7709                t.traceEnd();
7710            } else {
7711                Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
7712                        + currentUserId);
7713            }
7714
7715            t.traceBegin("resumeTopActivities");
7716            mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
7717            t.traceEnd();
7718
7719            if (bootingSystemUser) {
7720                t.traceBegin("sendUserSwitchBroadcasts");
7721                mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
7722                t.traceEnd();
7723            }
7724
7725            t.traceBegin("setBinderProxies");
7726            BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
7727                    BINDER_PROXY_LOW_WATERMARK);
7728            BinderInternal.nSetBinderProxyCountEnabled(true);
7729            BinderInternal.setBinderProxyCountCallback(
7730                    (uid) -> {
7731                        Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
7732                                + Process.myUid());
7733                        BinderProxy.dumpProxyDebugInfo();
7734                        if (uid == Process.SYSTEM_UID) {
7735                            Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
7736                        } else {
7737                            killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
7738                                    "Too many Binders sent to SYSTEM");
7739                        }
7740                    }, mHandler);
7741            t.traceEnd(); // setBinderProxies
7742
7743            t.traceEnd(); // ActivityManagerStartApps
7744            t.traceEnd(); // PhaseActivityManagerReady
7745        }
7746    }
 

SystemReady 主要做了以下事情:
1、回调几个服务的SystemReady方法,如AppOps;
2、kill 掉非persistent app进程。
3、启动 persistent app。
4、启动Home Activity 如Launcher

总结

总结AMS的启动流程如下图。

文章来自个人专栏
Android
15 文章 | 1 订阅
0条评论
作者已关闭评论
作者已关闭评论
1
1