Android之AMS

Kornan
2023-01-03 / 0 评论 / 162 阅读 / 正在检测是否收录...

AMS全称ActivityManagerService,AMS是Android中最核心的服务,主要负责系统中四大组件的启动、切换、调度及应用进程的管理和调度等工作,其职责与操作系统中的进程管理和调度模块相类似,因此它在Android中非常重要。

  1. 统一调度所有应用程序的Activity的生命周期
  2. 启动或杀死应用程序的进程
  3. 启动并调度Service的生命周期
  4. 注册BroadcastReceiver,并接收和分发Broadcast
  5. 启动并发布ContentProvider
  6. 调度task
  7. 处理应用程序的Crash
  8. 查询系统当前运行状态
    ActivityManagerService是在SystemServer.java中启动的。SystemServer会根据顺序依次启动各个服务:
        // Start services.
        try {
            traceBeginAndSlog("StartServices");
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
            SystemServerInitThreadPool.shutdown();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            traceEnd();
        }

执行startBootstrapServices函数:

// Activity manager runs the show.
        traceBeginAndSlog("StartActivityManager");
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        traceEnd();
        ……

这里启动了ActivityManagerService.Lifecycle.class服务,

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

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

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

        public ActivityManagerService getService() {
            return mService;
        }
    }

在startService中调用了ActivityManagerService的onStart()方法来启动该服务:

public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = System.currentTimeMillis();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
    }
0

评论

博主关闭了当前页面的评论