AMS服务的启动

QuibblerQuibbler 2020-07-16 约 22 分钟 2356 次阅读

AMS服务的启动

Android开发是不是经常听说过AMS,什么是AMS?其实指的就是ActivityManagerService和一些关联的类,对系统运行时的Activity进行管理。

以Android Q的源码开始阅读,了解AMS的启动过程,会发现不再由ActivityManagerService,而是由重构之后ActivityTaskManagerService类来启动管理Activity。

1、AMS启动Activity

之前分析过Activity的启动,见Activity启动流程源码分析一文,了解Activity启动的流程。在Activity启动的时候用到的就是ActivityTaskManagerService:

...
       try {
            intent.migrateExtraStreamToClipData();
            intent.prepareToLeaveProcess(who);
            int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } 
    ...

通过ActivityTaskManager类,在framework应用层调用getService()方法返回获取ActivityTaskManagerService单实例对象

public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    
    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

通过AMS来启动Activity,这里就不重复追踪了。

2、AMS的启动

AMS是系统服务,随着系统SystemServer的启动中启动,关于SystemServer的启动参考《SystemServer系统服务启动》。接着SystemServer的main()方法:

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

在run()方法中执行并初始化,执行加载各种系统服务,Android把系统服务分为三类:引导服务、核心服务、其它服务。

        startBootstrapServices():ActivityManagerService、DeviceIdentifiersPolicyService、LightsService等服务;

        startCoreServices():BatteryService、WebViewUpdateService、BinderCallsStatsService、GpuService、UsageStatsManagerInternal等服务;

        startOtherServices():KeyChainSystemService、TelecomLoaderService、DropBoxManagerService、AlarmManagerService、VrManagerService、BluetoothService、PinnerService、NetworkWatchlistService、NetworkScoreService、WifiScanningService等

private void run() {
        try {
            ...
            // 创建SystemServiceManager
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            // Prepare the thread pool for init tasks that can be parallelized
            SystemServerInitThreadPool.get();
        }
        try {
            //启动引导服务
            startBootstrapServices();
            //启动核心服务
            startCoreServices();
            //启动其它服务
            startOtherServices();
        }
        ...
        // Loop forever.
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

AMS属于系统引导服务,在startBootstrapServices()方法中初始化,ActivityManagerService在com.android.server.am包中,而ActivityTaskManagerService在com.android.server.wm包中。

private void startBootstrapServices() {
        ...
        // Activity manager runs the show.
        // 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();
        
        // 为系统进程设置Application实例并开始使用。
        mActivityManagerService.setSystemProcess();
        ...
    }

2.1、ActivityTaskManagerService启动

通过SystemServiceManager的startService(String className)方法,通过Service类名启动对应的Service

/**
     * Starts a service by class name.
     */
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            serviceClass = (Class<SystemService>)Class.forName(className);
        } 
        ...
        return startService(serviceClass);
    }

通过服务的类名,创建对应的Class实例

public <T extends SystemService> T startService(Class<T> serviceClass) {
        ...
            final T service;
            try {
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            }
            ...
            startService(service);
            return service;
        ...
    }

返回AMS服务实例之前还有一重要一步:

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();
        }
        ...
    }

①在系统中注册该服务,就是将启动的系统服务加入到集合统一管理

// Services that should receive lifecycle events.
    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

②启动AMS服务实例

try {
            service.onStart();
        }

调用ActivityTaskManagerService的onStart()方法

public void onStart() {
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            mService.start();
        }

mService就是ActivityTaskManagerService.Lifecycle类中保存的ActivityTaskManagerService实例

private void start() {
        LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
    }

调用LocalServices的静态方法addService(),将指定接口的服务实例添加到本地服务的全局注册表中。

/**
     * Adds a service instance of the specified interface to the global registry of local services.
     */
    public static <T> void addService(Class<T> type, T service) {
        synchronized (sLocalServiceObjects) {
            if (sLocalServiceObjects.containsKey(type)) {
                throw new IllegalStateException("Overriding service registration");
            }
            sLocalServiceObjects.put(type, service);
        }
    }

LocalServices类很特殊,维护一个静态的集合

private LocalServices() {}
    
    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
            new ArrayMap<Class<?>, Object>();

LocalServices类的使用方式与ServiceManager相似,不同之处在于,在LocalServices注册的服务不是Binder对象,只能在同一进程中使用。一旦将所有服务转换为SystemService接口,则可以将其吸收到SystemServiceManager中。

最后:因为返回的是ActivityTaskManagerService.Lifecycle类型对象,所以最好还是需要调用了getService()方法,返回Lifecycle中的ActivityTaskManagerService类型mService:

public ActivityTaskManagerService getService() {
        return mService;
    }

2.2、ActivityManagerService启动

紧接着ActivityTaskManagerService启动的就是AMS。

启动方式和ActivityTaskManagerService看着不太一样,ActivityTaskManagerService是借助SystemServiceManager的startService()方法,其实AMS也是借助了ActivityManagerService.Lifecycle的startService()方法,内部还是调用SystemServiceManager的startService()方法:

public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
    }

中间步骤和前面的ActivityTaskManagerService一样,唯一区别可能在于service.onStart()方法不同,最后调用ActivityManagerService的start()方法

private void start() {
        removeAllProcessGroups();
        mProcessCpuThread.start();
        mBatteryStatsService.publish();
        mAppOpsService.publish(mContext);
        Slog.d("AppOps", "AppOpsService published");
        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
        mActivityTaskManager.onActivityManagerInternalAdded();
        mUgmInternal.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        // Wait for the synchronized block started in mProcessCpuThread,
        // so that any other access to mProcessCpuTracker from main thread
        // will be blocked during mProcessCpuTracker initialization.
        try {
            mProcessCpuInitLatch.await();
        } catch (InterruptedException e) {
            Slog.wtf(TAG, "Interrupted wait during start", e);
            Thread.currentThread().interrupt();
            throw new IllegalStateException("Interrupted wait during start");
        }
    }

最后getService()方法返回封装在ActivityManagerService.Lifecycle中的AMS类型对象mService。

AMS完成了在系统Service服务中的注册,并且已经启动。

相关推荐

精选
ViewPager和PagerAdapter、FragmentPagerAdapter、FragmentStatePager
Android

ViewPager和PagerAdapter、FragmentPagerAdapter、FragmentStatePager

ViewPager1、ViewPagerandroidx.viewpager.widget.ViewPager,Android中使用非常广泛的控件,可以说是APP必备:首次打开引导页、页面Banner广告等。常用方法:setAdapter() 设置适配器setOffscreenPageLimit() 设置缓存的页面个数,默认是 1setCurrentItem() 跳转到特定的页面setOnPage

1.1k
获取Android内置WebView内核版本
Android

获取Android内置WebView内核版本

获取Android内置WebView内核版本竟然能遇到这样奇葩的事情,网页用的技术过于新颖,以至于只支持高版本Chromium内核的,低版本安卓系统中内置的内核版本较低,无法加载前端页面。1、设置查看在系统设置里 > 应用 > 应用管理 > 显示系统应用,查看WebView组件:2、页面查看通过WebView发起的网络请求,都会带上浏览器的UA,通常页面都可以通过UA判断浏览器的内核版本。这里有两

1.1w
Android 14适配总结
Android

Android 14适配总结

Android 14适配总结毕业工作至今已经适配了三个Android大版本,从Android 11到Android 12、再到Android 13。2023年,Google即将推出的Android 14,上半年已经开始第一批适配。现在,第四个Android版本已经适配完,总结记录一下。1、Android 14计划Google一般会在2月份对外发布预告,同时放出开发者预览版。“拉通”各大平台、厂商以

1.1w