AMS是系统的引导服务,应用进程的启动、切换和调度、四大组件的启动和管理都需要AMS的支持

AMS 启动

AMS 在 SystemServer.java 中启动

public void main(String[] args) {
    new SystemServer().run();
}
public void run() {
    ...
    // Initialize native services.
    System.loadLibrary("android_servers"); // 加载动态库
    ...
    // Create the system service manager.
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
    // Start services.
    try {
        t.traceBegin("StartServices");
        startBootstrapServices(t); // 引导服务:AMS、PMS等共7个
        /// M: For mtk systemserver
        sMtkSystemServerIns.startMtkBootstrapServices();
        startCoreServices(t); // 核心服务:BatteryService、UsageStatsService、WebViewUpdateService
        /// M: for mtk other service.
        sMtkSystemServerIns.startMtkCoreServices();
        startOtherServices(t); // 其他服务:70+
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        t.traceEnd(); // StartServices
    }
}

private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    // 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();
    ...
    // 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();
}

调用了SystemServiceManager.startService方法,参数是ActivityManagerService.Lifecycle.class:

public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        ...
        final T service;
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext); // 创建Lifecycle类型的service对象
        } catch (...) {
            ...
        }
        // Register it.
        mServices.add(service);
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart(); // 启动service
        } catch (...) {
            ...
        }
        return service;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
}

Lifecycle是AMS的内部类

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

    public Lifecycle(Context context) { // 创建Lifecycle实例时创建AMS实例
        super(context);
        mService = new ActivityManagerService(context, sAtm);
    }
    @Override
    public void onStart() {
        mService.start(); //启动service
    }
    public ActivityManagerService getService() {
        return mService; // 返回创建好的AMS实例
    }
}

管理

通过Activity启动过程分析AMS如何管理Activity

  1. activity向Instrumentation请求创建

  2. Instrumentation通过AMS在本地进程的IBinder接口,访问AMS,这里采用的跨进程技术是AIDL。

  3. 然后AMS进程一系列的工作,如判断该activity是否存在,启动模式是什么,有没有进行注册等等。

  4. 通过ClientLifeCycleManager,利用本地进程在系统服务进程的IBinder接口直接访问本地ActivityThread。

  5. ApplicationThread接收到服务端的事务后,把事务直接转交给ActivityThread处理。

  6. ActivityThread通过Instrumentation利用类加载器进行创建实例,同时利用Instrumentation回调activity的生命中周期

Activity 启动

Android App启动流程详解

Activity.startActivity() -> Activity.startActivityForResult()

判断是否创建新的Task、是否显示启动动画、以及获取多用户的用户句柄等等。

-> Instrumentation.java

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    ...  
    try {
        intent.migrateExtraStreamToClipData(who);
        intent.prepareToLeaveProcess(who);
        int result = ActivityTaskManager.getService().startActivity(whoThread,
                who.getOpPackageName(), who.getAttributionTag(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }       
}

Instrumentation 是系统进程和App进程交互的监测类,采用AIDL的形式获取到了 ActivityTaskManagerService 的代理类,然后跨进程通信通知 ActivityTaskManagerService 调用 startActivity 方法启动 activity

Activity 销毁

Activity.finish()

public void finish() {
    finish(DONT_FINISH_TASK_WITH_ACTIVITY);
}
private void finish(int finishTask) {
    ...
    if (ActivityClient.getInstance().finishActivity(mToken, resultCode, resultData,
            finishTask)) {
        mFinished = true;
    }
    ...
}

server 管理

AMS 收到启动 Activity 的请求后调用 startActivity(设置启动模式等)-> startActivityLocked 创建 ActivityStack,ActivityStack 中会用 WindowManager 进行一些切换窗口操作。

随后通过 Zygote 为 activity fork新的进程,来到 ActivityThread 的 main 方法,初始化启动 Looper、Handler 消息机制

197ce859-5a48-4311-8ee5-3f7b69e92271.png

  • ActivityRecord:一个 ActivityRecord 对应一个 Activity 实例,一个 Activity 根据其 launchMode 可能存在多个实例,因此会对应多个 ActivityRecord。ActivityRecord 中有 task 对象标识其归属的 TaskRecord。

  • TaskRecord:保存一组 ActivityRecord 信息,可以理解为 ActivityRecord 组成的栈。

  • ActivityStack:管理 TaskRecord。

任务栈模型:

48d4937f-6063-4488-8ede-881551d1445d.png

启动模式(Launch Mode):

  • standard:标准模式(默认),每次启动activity都会创建新实例

  • singleTop:栈顶复用,若新activity已经位于栈顶,那么不会创建新实例

  • singleTask:栈内复用,若新activity在栈内存在实例,那么不会创建新实例

  • singleInstance:任务栈中只允许这一个实例存在

Android进程管理篇总结