ActivityManagerService源码解析

ActivityManagerService源码解析

提示:本文基于android13的源码



前言

ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系统服务之一。ActivityManagerService(以下简称AMS)主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。所有的APP应用都需要与AMS打交道。
ActivityTaskManager的组成主要分为以下几个部分:
1、服务中枢:由ActivityTaskManager实现,在内部存储服务代理对像IActivityTaskManagerSingleton,并提供了getService方法返回服务代理;
2、服务代理:IActivityTaskManagerSingleton是Singleton的实现类,在create方法中获取了ActivityTaskManagerService的Binder代理对像的引用,通过泛型实现IActivityTaskManager。


一、ActivityManagerService的初始化

AMS的启动是从是从SystemServer的main方法开始的。

/**
 * zygote的调用入口
 */
public static void main(String[] args) {
    new SystemServer().run();
}
private void run() {
......
    try {
        ......
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
        ......
    // 开启服务.
    try {
        t.traceBegin("StartServices");
        t.traceBegin("StartServices");
       //启动引导服务,如:ATMS、AMS、DMS、PMS、UMS
       startBootstrapServices(t);
       //启动核心服务,如:BatteryService,UsageStatsService,WebViewUpdateService
       startCoreServices(t);
       //启动其它服务,如:WindowManagerService、AlarmManagerService、CachedDeviceStateService、VibratorManagerService等等
       startOtherServices(t);
       //启动在顶点(Apex)中定义的系统服务,是最后一类启动的服务。在此之后,不得启动任何其他服务。这是为了防止在OTA之外更新这些顶点时出现不必要的稳定性问题;并避免将依赖关系从系统分解为顶点。
       startApexServices(t);
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        t.traceEnd(); // StartServices
    }
    ......
    // Loop forever.
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

系统启动了四类服务:引导服务、核心服务、其他服务和顶点服务,并开启了loop循环,来接收其它进程发过的消息。其中AMS就在引导服务中启动的,代码如下:

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    ......
    // Activity manager runs the show.
    t.traceBegin("StartActivityManager");
    // 启动ATMS
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
    // 启动AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
    // 设置系统管理服务
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    // 设在应用管理
    mActivityManagerService.setInstaller(installer);
    // 获取window的全局锁
    mWindowManagerGlobalLock = atm.getGlobalLock();
     t.traceEnd();
    ......
    mActivityManagerService.setSystemProcess();
    ......
}

1、ActivityTaskManagerService初始化

在这里插入图片描述
从android10开始,AMS的内容就包含ActivityTaskManagerService,它分担了AMS启动与管理Activity部分。

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + name);
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

        // Create the service.
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
            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);
    }
}

startService方法中传入的是ActivityTaskManagerService.Lifecycle.class,通过这个class获取了类的名词、构造方法,注意这个构造方法:

public static final class Lifecycle extends SystemService {
    private final ActivityTaskManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityTaskManagerService(context);
    }
   ......
}

这里面实例化了ActivityTaskManagerService,里面作很多事情,见代码注释。

public ActivityTaskManagerService(Context context) {
    //缓存SystemServer的上下文
    mContext = context;
    mFactoryTest = FactoryTest.getMode();
    //获取ActivityThread,这个ActivityThread代表SystemServer
    mSystemThread = ActivityThread.currentActivityThread();
    //获取基于用于UI的系统资源和显示信息的上下文实例。
    mUiContext = mSystemThread.getSystemUiContext();
    //能够组合多个客户端生命周期转换请求和/或回调,并将它们作为单个事务执行。
    mLifecycleManager = new ClientLifecycleManager();
    //快速查找具有可见Activity的所有进程。它还跟踪具有前台(恢复)Activity的home进程的CPU使用情况。
    mVisibleActivityProcessTracker = new VisibleActivityProcessTracker(this);
    // ActivityTaskManagerInternal的子类,ActivityTaskManagerInternal是Activity任务管理器本地系统服务接口。
    mInternal = new LocalService();
    GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
    // 用于组织窗口的接口的服务器端实现
    mWindowOrganizerController = new WindowOrganizerController(this);
    mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
    mTaskFragmentOrganizerController =
            mWindowOrganizerController.mTaskFragmentOrganizerController;
    // 在服务器端处理与后退手势相关的动作的控制器
    mBackNavigationController = BackNavigationController.isEnabled()
            ? new BackNavigationController() : null;
}

接着调用了startService方法,

public void startService(@NonNull final SystemService service) {
    // Check if already started
    String className = service.getClass().getName();
    if (mServiceClassnames.contains(className)) {
        Slog.i(TAG, "Not starting an already started service " + className);
        return;
    }
    mServiceClassnames.add(className);

    // Register it.
    mServices.add(service);

    // Start it.
    long time = SystemClock.elapsedRealtime();
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + service.getClass().getName()
                + ": onStart threw an exception", ex);
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

在这里面,将service添加进mServices集合,这一个SystemService集合,SystemServer就是通过这个集合来管理服务的。接着调用ActivityTaskManagerService.Lifecycle的onStart方法。

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

通过publishBinderService方法将服务发布给ServiceManager管理,看下面的方法,也就被添加进取了。这样其它进程可以通过ServiceManager获取ActivityTaskManagerService的Binder代理对象,使用ActivityTaskManagerService。

protected final void publishBinderService(String name, IBinder service,
        boolean allowIsolated, int dumpPriority) {
    ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}

mService.start();调用的是ActivityTaskManagerService的start方法。

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

在这个方法中ActivityTaskManagerInternal添加给LocalServices管理,这样在本进程的其它地方要使用LocalService提供的服务,这里就不详细介绍了。

2、ActivityManagerService初始化

在这里插入图片描述

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

这个方法里面把ActivityTaskManagerService 赋值给sAtm,然后调用SystemServiceManager 的startService和SystemServiceManager.Lifecycle.getService方法。

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
        Slog.i(TAG, "Starting " + name);
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

        // Create the service.
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }


        final T service;
        try {
            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);
    }
}

获取ActivityManagerService.Lifecycle的构造方法,并调用它

public Lifecycle(Context context) {
    super(context);
    mService = new ActivityManagerService(context, sAtm);
}

这里面创建了ActivityManagerService实例。

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

    mFactoryTest = FactoryTest.getMode();
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

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

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

    // bind background threads to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    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();
    mTraceErrorLogger = new TraceErrorLogger();
    mComponentAliasResolver = new ComponentAliasResolver(this);
}

接着调用startService

public void startService(@NonNull final SystemService service) {
    // Check if already started
    String className = service.getClass().getName();
    if (mServiceClassnames.contains(className)) {
        Slog.i(TAG, "Not starting an already started service " + className);
        return;
    }
    mServiceClassnames.add(className);

    // Register it.
    mServices.add(service);

    // Start it.
    long time = SystemClock.elapsedRealtime();
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        throw new RuntimeException("Failed to start service " + service.getClass().getName()
                + ": onStart threw an exception", ex);
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

调用ActivityManagerService.Lifecycle的onStart方法

@Override
public void onStart() {
    mService.start();
}

调用ActivityManagerService的start方法

private void start() {
    mBatteryStatsService.publish();
    mAppOpsService.publish();
    mProcessStats.publish();
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, mInternal);
    LocalManagerRegistry.addManager(ActivityManagerLocal.class,
            (ActivityManagerLocal) mInternal);
    mActivityTaskManager.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    mAppProfiler.onActivityManagerInternalAdded();
    CriticalEventLog.init();
}

LocalServices:使用方式与ServiceManager类似,但此处注册的服务不是Binder对象,只能在同一进程中使用。一旦所有服务都转换为SystemService接口,这个类就可以被吸收到SystemServiceManager中。
LocalManagerRegistry:进程内模块接口的注册表,它维护一个map,可以通过它拿到注册的服务。
PendingIntentControlle:ActivityManagerService的帮助程序类,负责管理挂起的意图。此类使用mLock来同步对内部状态的访问,并且不使用ActivityManagerService锁,因为可以从AM外部直接调用此类。这有助于避免死锁。
AppProfiler一个助手类,负责应用程序的评测、内存和cpu采样 。
CriticalEventLog:最近关键事件的日志,如看门狗。用于在ANR报告中显示可能有助于调试ANR的最近事件。特别是,最近关键事件的出现表明设备已经处于故障状态。该类需要是线程安全的,因为它被用作单例。
从上面代码看AMS已经初始化,当怎么没有像ATMS那个把自己注册到ServiceManager,提供给其它进程使用呢?
其实这个注册是setSystemProcess方法中。

public void setSystemProcess() {
    try {
        // 注册服务ActivityManagerService
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
        // 注册服务procstats,进程状态
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        // 注册服务meminfo,内存信息
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        // 注册服务gfxinfo,图像信息
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        // 注册服务dbinfo,数据库信息
        ServiceManager.addService("dbinfo", new DbBinder(this));
        //注册服务cpuinfo,cpu信息
        mAppProfiler.setCpuInfoService();
        //注册服务permission和processinfo,权限和进程信息
        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维护进程的相关信息
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    false,
                    0,
                    null,
                    new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM));
            app.setPersistent(true);
            app.setPid(MY_PID);
            app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM);
            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);
    }

    // 在我们和包管理器启动并运行后,开始观察应用程序操作。
    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);
        }
    });
}

注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务注册到ServiceManager,从这里可以看出AMS对主要设备组件和进程的管理。查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的installSystemApplicationInfo方法,来实现系统应用安装。创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个ProcessRecord类型的对象,并保存该对象的信息。使用mAppOpsService来观察和跟踪应用程序操作与控制的相关信息。

3、思考

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
......
    // Activity manager runs the show.
    t.traceBegin("StartActivityManager");
    // 启动ATMS
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
    // 启动AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
    // 设置系统管理服务
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    // 设在应用管理
    mActivityManagerService.setInstaller(installer);
    // 获取window的全局锁
    mWindowManagerGlobalLock = atm.getGlobalLock();
     t.traceEnd();
......
}

在为什么在startBootstrapServices中startService传递的是ActivityTaskManagerService.Lifecycle.class而不是ActivityTaskManagerService?
ActivityTaskManagerService是给谁使用的?是给其它进程使用的,ActivityTaskManagerService运行在system_server进程中,一般称system_server服务端,app为客户端。ActivityTaskManagerService是提供给app来使用的。所以ActivityTaskManagerService继承IActivityTaskManager.Stub,IActivityTaskManager.Stub是一个Ibinder,用于跨进程。所以它只能IActivityTaskManager.Stub,不能继承SystemService。SystemServer里面启动一百多个服务这些服务通过SystemServiceManager进行管理,管理这些服务需要它们具备某一些相同的特征,所以这些服务都有继承了SystemService。因为java是单继承语言,所以这里使用ActivityTaskManagerService的内部类Lifecycle继承SystemService,Lifecycle在初始化的时候,实例化ActivityTaskManagerService,并持有它,等SystemServer向Lifecycle发出管理动作的时,把这些动作转发给ActivityTaskManagerService,比如通过onStart方法初始化服务。使用静态内部类从而解决java中单继承问题。

二、堆栈管理

待后续


三、生命周期管理

待后续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值