如何应对Android面试官 -> ActivityManagerService 是怎么启动的?

前言


image.png

本章主要讲解下 什么是 AMS,以及它是如何启动的;

SystemServer


SystemServer 通过按下电源键接通电源之后就会启动 BootRoom,BootRoom 就会拉起一个 BootLoader 程序,此程序会拉起 Linux Kernel「系统内核」,我们的 Android 系统就会初始化一个用户态进程也就是 init 进程,init 进程会执行 initZygote.rc 创建 zygote 进程,zygote 进程会 fork「孵化」出 SystemServer「系统服务进程,这是 zygote 进程的最大的一个儿子,Android 上层需要的所有服务例如 AMS,WMS,PMS,PKMS 等等都会在 SystemServer 初始化起来」 SystemServer 进程就会拉起我们的第一个应用程序「也就是桌面程序 Launcher 进程」;

image.png

这是一个 Android GUI 关系图;

AMS 是什么?


从 java 角度来看,AMS 就是一个 java 对象,实现了 Ibinder 接口,所以它是一个用于进程之间通信的接口,这个对象初始化是在 SystemServer.java 的 run() 方法里面;

ActivityManagerService 从名字就可以看出,它是一个服务,用来管理 Activity,而且是一个系统服务,就是包管理服务,电池管理服务,震动管理服务等;

AMS 实现了 Ibinder 接口,所以它是一个 Binder,这意味着他不但可以用于进程间通信,还是一个线程,因为一个 Binder 就是一个线程;

总得来说:ActivityManagerService 是 Android 系统中一个特别重要的系统服务,也是我们上层 APP 打交道最多的系统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。所有的 APP 应用都需要与 AMS 打交道 ActivityManager 的组成主要分为以下几个部分:

1.服务代理:由 ActivityManagerProxy 实现,用于与 Server 端提供的系统服务进行进程间通信;

2.服务中枢:ActivityManagerNative 继承自 Binder 并实现 IActivityManager,它提供了服务接口和Binder 接口的相互转化功能,并在内部存储服务代理对象,并提供了 getDefault 方法返回服务代理;

3.Client:由 ActivityManager 封装一部分服务接口供 Client 调用。ActivityManager 内部通过调用ActivityManagerNative 的 getDefault 方法,可以得到一个 ActivityManagerProxy 对象的引用,进而通过该代理对象调用远程服务的方法;

4.Server:由 ActivityManagerService 实现,提供 Server 端的系统服务;

AMS 启动流程


SystemServer 创建之后,就会调研 run 方法,这个 run 方法就会启动 AMS;

createSystemContext

创建进程,启动launcher,把界面显示出来,会需要大量的资源,例如「文字,图片」,想要获取这些资源,都需要context,而系统的资源获取 也需要一个 context 对象,所以创建一个系统级别的 context 来获取资源,系统资源的加载都是在这个时候被加载的。例如「@android/xxx等都属于系统资源」;

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

这里重点关注的时候 ActivityThread.systemMain() 方法,我们进入这个方法看下:

public static ActivityThread systemMain() {
    ThreadedRenderer.initForSystemProcess();
    ActivityThread thread = new ActivityThread();
    thread.attach(true, 0);
    return thread;
}

这里创建了 ActivityThread 已经进行了 attach 操作;

ActivityThread() {
    mResourcesManager = ResourcesManager.getInstance();
}

获取资源管理实例;

private void attach(boolean system, long startSeq) {
    
    if (!system) {
        // 省略部分代码
    } else {
        try {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to instantiate Application():" + e.toString(), e);
        }
    }
    // 省略部分代码
}

这里做了三件事情

  1. new Instrumentation(); 创建 Instrumentation;
  2. ContextImpl.createAppContext(this, getSystemContext().mPackageInfo) 根据 LoadApk 对象创建 Context;
  3. context.mPackageInfo.makeApplication(true, null); 初始化 Application;

getSystemContext


其中 createAppContext 需要获取 SystemContext 作为入参,我们进入这个方法看下:

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}

我们进入这个 createSystemContext 看下:

static ContextImpl createSystemContext(ActivityThread mainThread) {
    LoadedApk packageInfo = new LoadedApk(mainThread);
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
            ContextParams.EMPTY, null, null, null, null, null, 0, null, null);
    context.setResources(packageInfo.getResources());
    context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
            context.mResourcesManager.getDisplayMetrics());
    context.mContextType = CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI;
    return context;
}

这个方法做了两件事情,

  1. 创建 LoadedApk 对象,通过 LoadeApk 获取每一个安装在手机上的 APK 信息;
  2. 创建ContextImpl,首次执行getSystemContext会执行createSystemContext创建LoadedApk和contextImpl对象,利用刚创建的LoadedApk创建contextImpl;

createAppContext

ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,null);
context.setResources(packageInfo.getResources());

startBootstrapService

启动一系列相关引导服务,我们进入源码看下:

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {

    // 省略部分代码
    
    // 启动 APK 安装服务
    Installer installer = mSystemServiceManager.startService(Installer.class);
    // 省略部分代码
    
    // 启动 AMS 服务
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    // 设置 SystemServiceManager        
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    // 设置 APK 安装器
    mActivityManagerService.setInstaller(installer);
    
    // 初始化 AMS 相关的PMS 
    mActivityManagerService.initPowerManagement();
    // 设置 SystemServer
    mActivityManagerService.setSystemProcess();
}

startCoreServices();

启动核心服务,我们进入这个源码看下:

private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
    
    mSystemServiceManager.startService(SystemConfigService.class);

    mSystemServiceManager.startService(BatteryService.class);

    mSystemServiceManager.startService(UsageStatsService.class);
    // 启动用户统计服务
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));
    
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

    mSystemServiceManager.startService(CachedDeviceStateService.class);

    mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);

    mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

    mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);

    mSystemServiceManager.startService(NativeTombstoneManagerService.class);

    mSystemServiceManager.startService(BugreportManagerService.class);

    mSystemServiceManager.startService(GpuService.class);
}

startOtherServices()

启动其他服务,我们进入这个方法看下:

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
    // 省略部分代码
    
    // 安装系统的 provider
    mActivityManagerService.installSystemProviders();
    
    // 设置 windowManager
    wm = WindowManagerService.main(context, inputManager,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
                    !mFirstBoot, mOnlyCore, new PhoneWindowManager());
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    mActivityManagerService.setWindowManager(wm);
    // 设置 inputManager
    inputManager = new InputManagerService(context);
    ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    // 通知
    mSystemServiceManager.startService(NotificationManagerService.class);
    
    mActivityManagerService.systemReady();
}

AMS 服务启动流程


这里额外插一句,service_manager 和 SystemServiceManager 的区别,service_manager 是 C/C++ 层的,用来管理 binder 服务的大管家,而 SystemServiceManager 是用来管理各种服务的启动,每启动一个服务,都会收集到一个 mServices 的集合中;

mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);

这里并不是直接 new 出来 AMS,而是通过 LifeCycle 这个代理类来创建 AMS,而 LifeCycle 的创建是通过反射来实现的,LifeCycle 在初始化的时候会初始化 AMS,我们进入这个 LifeCycle 看下:

public static final class Lifecycle extends SystemService {
    
    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityManagerService(context, sAtm);
    }
    
    
    public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
    }
    
    @Override
    public void onBootPhase(int phase) {
        mService.mBootPhase = phase;
        if (phase == PHASE_SYSTEM_SERVICES_READY) {
            mService.mBatteryStatsService.systemServicesReady();
            mService.mServices.systemServicesReady();
        } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
            mService.startBroadcastObservers();
        } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
            mService.mPackageWatchdog.onPackagesReady();
        }
    }
    
    // 返回 AMS
    public ActivityManagerService getService() {
        return mService;
    }
}

LifeCycle 继承 SystemService,这个 com.android.server.SystemService 中包含了系统服务启动的各个阶段;

public abstract class SystemService {

    /** @hide */
    protected static final boolean DEBUG_USER = false;

    /**
     * The earliest boot phase the system send to system services on boot.
     */
    public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;

    /**
     * Boot phase that blocks on SensorService availability. The service gets started
     * asynchronously since it may take awhile to actually finish initializing.
     *
     * @hide
     */
    public static final int PHASE_WAIT_FOR_SENSOR_SERVICE = 200;

    /**
     * After receiving this boot phase, services can obtain lock settings data.
     */
    public static final int PHASE_LOCK_SETTINGS_READY = 480;

    /**
     * After receiving this boot phase, services can safely call into core system services
     * such as the PowerManager or PackageManager.
     */
    public static final int PHASE_SYSTEM_SERVICES_READY = 500;

    /**
     * After receiving this boot phase, services can safely call into device specific services.
     */
    public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

    /**
     * After receiving this boot phase, services can broadcast Intents.
     */
    public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

    /**
     * After receiving this boot phase, services can start/bind to third party apps.
     * Apps will be able to make Binder calls into services at this point.
     */
    public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

    /**
     * After receiving this boot phase, services can allow user interaction with the device.
     * This phase occurs when boot has completed and the home application has started.
     * System services may prefer to listen to this phase rather than registering a
     * broadcast receiver for {@link android.content.Intent#ACTION_LOCKED_BOOT_COMPLETED}
     * to reduce overall latency.
     */
    // 代表着 服务 启动完成
    public static final int PHASE_BOOT_COMPLETED = 1000;
}

我们接着拐回去看 LifeCycle 的 startService 方法,这个方法直接调用 SystemServiceManager 的 startService 方法,我们进入这个方法看下:

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
            // 使用反射创建 LifeCycle 对象;
            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);
        }

        startService(service);
        return service;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}

这里使用反射的方式来创建 LifeCycle 对象,当创建的,就会调用其构造方法,构造方法中就会创建 AMS,然后通过 getService 返回;

这个 LifeCycle 中创建的 mService 就是正儿八经的 ActivityManagerService,也就是我们需要的 AMS,这样做就会让 AMS 有一个生命周期;

SystemService 有各个阶段的状态分发,最终通过 LifeCycle 重写的 onBootPhase 分发具体逻辑,当分发PHASE_SYSTEM_SERVICES_READY 的时候,会执行 AMS 中的 ActiveServices 的 systemServiceReady 方法,这个 ActiveServices 就是用来管理四大组件的,就是说 AMS 通过操作 ActiveServices 来间接管理四大组件;

到此 AMS 就创建了出来了,接下来看下它在创建的时候都做了哪些事情,我们进入 AMS 的构造方法看下:

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector(systemContext);
    mContext = systemContext;

    mFactoryTest = FactoryTest.getMode();
    // 1. 创建 Android UI 线程
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);

    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mPlatformCompat = (PlatformCompat) ServiceManager.getService(
            Context.PLATFORM_COMPAT_SERVICE);
    mProcessList = mInjector.getProcessList(this);
    mProcessList.init(this, activeUids, mPlatformCompat);
    mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
            new LowMemDetector(this));
    mPhantomProcessList = new PhantomProcessList(this);
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

    final BroadcastConstants foreConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_FG_CONSTANTS);
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

    final BroadcastConstants backConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_BG_CONSTANTS);
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;

    final BroadcastConstants offloadConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

    mEnableOffloadQueue = SystemProperties.getBoolean(
            "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);

    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;
    // 2. 创建 ActiveServices 用来管理四大组件
    mServices = new ActiveServices(this);
    mCpHelper = new ContentProviderHelper(this, true);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    mUidObserverController = new UidObserverController(mUiHandler);

    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"));

    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

    mUserController = new UserController(this);

    mPendingIntentController = new PendingIntentController(
            mHandlerThread.getLooper(), mUserController, mConstants);

    mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

    mActivityTaskManager = atm;
    // 创建 recentTasks、ActivityStartController
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

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

    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }

    mInternal = new LocalService();
    mPendingStartActivityUids = new PendingStartActivityUids(mContext);
    mTraceErrorLogger = new TraceErrorLogger();
}

AMS的创建做了五个比较重要的事情

  1. 创建 Android UI 线程;mSystemThread = ActivityThread.currentActivityThread();
  2. 创建 ActiveService;mServices = new ActiveServices(this);
  3. 创建管理 Activity 的 ActivityStackSupervisor 对象;mStackSupervisor = new ActivityStackSupervisor(this, mHandler.getLooper());
  4. 创建最近任务列表;mRecentTasks = new RecentTasks(this, mStackSupervisor);
  5. 创建 App的 Activity 生命周期管理类;mLifeCycleManager = n ew ClientLifeCycleManager();

初始之后,我们来看下 start 逻辑

private void start() {
    // AMS 启动的时候会把所有的应用进程移除掉
    removeAllProcessGroups();
    // 启动电池统计服务
    mBatteryStatsService.publish();
    mAppOpsService.publish();
    LocalServices.addService(ActivityManagerInternal.class, mInternal);
    LocalManagerRegistry.addManager(ActivityManagerLocal.class,
            (ActivityManagerLocal) mInternal);
    mActivityTaskManager.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    mAppProfiler.onActivityManagerInternalAdded();
}

整个的 start 大致过程就结束了;

初始化 AMS 相关的 PMS

AMS 在 start 之后,会调用 mActivityManagerService.initPowerManagement(); 来初始化 PowerManagerService 服务,我们来看下这里面都做了什么

public void initPowerManagement() {
    mActivityTaskManager.onInitPowerManagement();
    mBatteryStatsService.initPowerManagement();
    mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}

逻辑还是比较简单的,初始化 PMS 相关服务;

设置 SystemServer

AMS 在 start 之后,会调用 mActivityManagerService.setSystemProcess(); 来设置 SystemServer

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

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

    final int[] cameraOp = {AppOpsManager.OP_CAMERA};
    mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
        @Override
        public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
                boolean active, @AttributionFlags int attributionFlags,
                int attributionChainId) {
            cameraActiveChanged(uid, active);
        }
    });
}

这里主要关注三点:

第一个是添加各种服务;

  1. activity AMS;ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
  2. procstats 进程统计;ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
  3. meminfo 内存;ServiceManager.addService(“meminfo”, new MemBinder(this));
  4. gfxinfo 图像信息;ServiceManager.addService(“gfxinfo”, new GraphicsBinder(this));
  5. dbinfo 数据库;ServiceManager.addService(“dbinfo”, new DbBinder(this));
  6. cpuinfo CPU;ServiceManager.addService(“cpuinfo”, new CpuBinder(this));
  7. permission 权限;ServiceManager.addService(“permission”, new PermissionController(this));
  8. processinfo 进程服务;ServiceManager.addService(“processinfo”, new ProcessInfoService(this));
  9. usagestats 应用的使用情况;

adb shell dumpsys 的各种服务的来源就是从这里添加进去的;

第二个是创建用于性能统计的Profiler对象;

ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
“android”, STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

第三个是创建ProcessRecord对象;

ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);

安装系统的 provider

在 startOtherService 方法中,会调用 mActivityManagerService.installSystemProviders(); 来安装系统的 provider

设置 WindowManager

在 startOtherService 方法中,会调用 mActivityManagerService.setWindowManager(wm); 设置窗口管理器;

public void setWindowManager(WindowManagerService wm) {
    synchronized (this) {
        mWindowManager = wm;
        mWmInternal = LocalServices.getService(WindowManagerInternal.class);
        mActivityTaskManager.setWindowManager(wm);
    }
}

设置windowManager

wm = WindowManagerService.main(context, inputManager,
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
                    !mFirstBoot, mOnlyCore, new PhoneWindowManager());
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);
mActivityManagerService.setWindowManager(wm); 

setWindowManager 中创建核心 Settings Observer,用于监控 Settings「系统设置」

mCoreSettingsObserver = new CoreSettingsObserver(this);

服务启动完成

当执行到 mActivityManagerService.systemReady 的时候,表示前面创建的80多个服务都已经启动完成了;
接下来需要启动系统UI、执行一系列服务的systemReady、启动 Luancher;

startSystemUi(context, windowManagerF); 启动 systemui 服务;

private static void startSystemUi(Context context, WindowManagerService windowManager) {
    PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    Intent intent = new Intent();
    intent.setComponent(pm.getSystemUiServiceComponent());
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    //Slog.d(TAG, "Starting service: " + intent);
    context.startServiceAsUser(intent, UserHandle.SYSTEM);
    windowManager.onSystemUiStarted();
}

mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY); 调用AMS服务的ready -> service.onBootPhase();

public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
    mCurrentPhase = phase;
    try {
        final int serviceLen = mServices.size();
        for (int i = 0; i < serviceLen; i++) {
            final SystemService service = mServices.get(i);
            long time = SystemClock.elapsedRealtime();
            try {
                service.onBootPhase(mCurrentPhase);
            } catch (Exception ex) {
            }
            warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
        }
    } finally {
    }

    if (phase == SystemService.PHASE_BOOT_COMPLETED) {
        final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
        SystemServerInitThreadPool.shutdown();
    }
}

startHomeActivityLocked(currentUserId, “systemReady”); 启动Launcher Android开机过程结束,就可以看到桌面使用手机;

到这里,AMS 的启动流程就结束了;

下一章预告


Activity 启动流程

欢迎三连


来都来了,点个关注,点个赞吧,你的支持是我最大的动力~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/536924.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

小程序如何通过把动态数据值传入到css文件中控制样式

场景&#xff1a;动态改变一个模块的高度 一、常用解决方法&#xff1a;行内样式绑值&#xff0c;或者动态class来传递 <viewclass"box":style"height: ${boxHeight}px">我是一个动态高度的box,我的高度是{{boxHeight}}px </view>二、高度传…

关于Linux下的进程替换(进程篇)

目录 进程替换是什么&#xff1f; 进程替换需要怎样操作&#xff1f; 替换函数 命名理解 不创建子进程进行进程替换 关于替换程序时的写时拷贝 fork创建子进程进行替换 函数1&#xff1a;execl 函数2&#xff1a;execv 函数3&#xff1a;execlp 函数4&#xff1a;execvp…

python-study-day1-(病人管理系统-带sql)

MainWindow代码 from tkinter import * from tkinter import messagebox from tkinter.ttk import Comboboxclass MianWindow(Frame):def __init__(self, masterNone):super().__init__(master, padx30, pady20)self.flag 0self.pack(expandTrue, fillBOTH)self.id StringVa…

vue3:菜单、标签页和面包屑联动效果

文章目录 1.整体思路2.实现过程 概要 提示&#xff1a;这里可以添加技术概要 例如&#xff1a; openAI 的 GPT 大模型的发展历程。 1.整体思路 在之前做的后台项目中&#xff0c;菜单、标签页和面包屑之间的联动&#xff0c;自己都是通过在路由前置守卫中&#xff0c;定义b…

铭飞SQL注入严重信息泄露【附POC】

感谢您抽出 阅读本文 MCMS是一个<完整开源的Java CMS&#xff01;基于SpringBoot 2架构&#xff0c;前端基于vue、element ui。MCMS存在SQL注入漏洞&#xff0c;攻击者可通过该漏洞获取数据库敏感信息等。目前厂商暂未发布修复措施解决此安全问题&#xff0c;建议使用此软件…

配置QtCreator能加载自定义插件的环境

配置对应环境 引言查看当前版本配置能够加载插件的环境 引言 生成的自定义插件能在QtCreator的设计器中加载&#xff0c;需要满足当前使用的QtCreator的编译时所需的Qt库和编译器。 查看当前版本 这里需要先查看自己使用的QtCreator的版本&#xff0c;即生成QtCreator时使用…

【LeetCode】回溯算法类题目详解

所有题目均来自于LeetCode&#xff0c;刷题代码使用的Python3版本 回溯算法 回溯算法是一种搜索的方法&#xff0c;在二叉树总结当中&#xff0c;经常使用到递归去解决相关的问题&#xff0c;在二叉树的所有路径问题中&#xff0c;我们就使用到了回溯算法来找到所有的路径。 …

淘宝1688京东店铺所有商品数据接口(item_search_shop接口系列,可测试)

淘宝、1688和京东都提供了API接口供开发者调用&#xff0c;以获取店铺和商品的详细数据。对于您提到的item_search_shop接口系列&#xff0c;这主要是用于获取店铺所有商品的数据。然而&#xff0c;具体的接口名称和功能可能会因平台而异&#xff0c;且可能随着平台的更新而有所…

LigaAI x 极狐GitLab,共探 AI 时代研发提效新范式

近日&#xff0c;LigaAI 和极狐GitLab 宣布合作&#xff0c;双方将一起探索 AI 时代的研发效能新范式&#xff0c;提供 AI 赋能的一站式研发效能解决方案&#xff0c;让 AI 成为中国程序员和企业发展的新质生产力。 软件研发是一个涉及人员多、流程多、系统多的复杂工程&#…

微服务面试题二

1.什么是雪崩 微服务之间相互调用&#xff0c;因为调用链中的一个服务故障&#xff0c;引起整个链路都无法访问的情况。 如何解决雪崩&#xff1f; 超时处理&#xff1a;请求超时就返回错误信息&#xff0c;不会无休止等待仓壁模式&#xff1a;限定每个业务能使用的线程数&a…

cordova后台插件开发新手教程

typora-root-url: imags cordova后台插件开发新手教程 预安装环境&#xff1a;JDK11、Android studios、nodo.js 一、环境搭建 1.安装Cordova npm install -g cordova2.创建项目 cordova create 具体命令&#xff1a; cordova create 目录名 包名 项目名 执行结果终端&am…

大模型RAG(三)检索环节(Retriever)

1. 搜索索引 &#xff08;1&#xff09;向量存储索引 最原始的实现是使用平面索引 — 查询向量和所有块向量之间的暴力计算距离。根据索引选择、数据和搜索需求&#xff0c;还可以存储元数据&#xff0c;并使用元数据过滤器来按照日期或来源等条件进行信息检索。LlamaIndex 支…

【实战JVM】打破双亲委派机制之线程上下文类加载器

个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名大三在校生&#xff0c;喜欢AI编程&#x1f38b; &#x1f43b;‍❄️个人主页&#x1f947;&#xff1a;落798. &#x1f43c;个人WeChat&#xff1a;hmmwx53 &#x1f54a;️系列专栏&#xff1a;&#x1f5bc;️…

CS与MSF联动/shell互相反弹

Cs的shell反弹到msf 参考资料:https://blog.csdn.net/Zlirving_/article/details/113862910 先建立监听器 先建立一个监听器&#xff0c;和msf的要一一对应&#xff0c;上面的ip必须是可以ping通的大部分情况是外网ip Msf&#xff1a; use exploit/multi/handler set paylo…

Netty学习——实战篇1 BIO、NIO入门demo 备注

1 BIO 实战代码 Slf4j public class BIOServer {public static void main(String[] args) throws IOException {//1 创建线程池ExecutorService threadPool Executors.newCachedThreadPool();//2 创建ServerSocketServerSocket serverSocket new ServerSocket(8000);log.in…

高清无水印短视频素材去哪找?今天讲五个素材网站,记得收藏

在视频剪辑的世界里&#xff0c;我就像是那个经常带着一副老花镜在宝藏地图上寻宝的老海盗。每次寻宝之旅&#xff0c;我都能从九才素材网这个家门口的宝藏开始&#xff0c;然后驾驶我的老旧剪辑船&#xff0c;航向国际的深蓝大海&#xff0c;寻找那些只属于知情者的秘密宝藏。…

【C++进阶】C++异常详解

C异常 一&#xff0c;传统处理错误方式二&#xff0c;C处理的方式三&#xff0c;异常的概念四&#xff0c;异常的使用4.1 异常和捕获的匹配原则4.2 函数调用链中异常栈展开匹配原则4.3 异常的重新抛出&#xff08;异常安全问题&#xff09;4.4 RAII思想在异常中的作用 五&#…

使用Java+Maven+TestNG进行自动化测试

写作背景&#xff1a;有点Java基础的功能测试人员&#xff08;点点点工程师&#xff09;&#xff0c;所在项目有"去QE"的趋势&#xff0c;所以自己要多点亮其他技能&#xff0c;让路子走宽点。 简单说一下去QE&#xff1a;项目测试不再有专职的测试工程师来做&#x…

计算机网络——40各个层次的安全性

各个层次的安全性 安全电子邮件 Alice需要发送机密的报文m给Bob Alice 产生随机的对称秘钥&#xff0c; K s K_s Ks​使用 K s K_s Ks​对报文进行加密&#xff08;为了效率&#xff09;对 K s K_s Ks​使用Bob的公钥进行加密发送 K s ( m ) K_s(m) Ks​(m)和 K B ( K S ) K…

小程序/app/H5多端圈子社区论坛系统交友/社交/陌生人社交即时聊天私域话题社区论坛 行业圈子小程序 微信社区小程序圈子论坛社区小程序

项目介绍 这是一个社区论坛类小程序项目源码&#xff0c;可以实现用户发送自定义图文内容&#xff0c;点赞&#xff0c;评论&#xff0c;回复&#xff0c;记录评论过的帖子&#xff0c;记录发表过的帖子&#xff0c;左滑删除&#xff0c;在线实时接收消息&#xff0c;离线接收…