Android核心技术【SystemServer加载AMS】

启动流程

  • Init 初始化Linux 层,处理部分服务

    • 挂载和创建系统文件

    • 解析rc文件:

      • rc 文件中有很多action
    • 进入无限循环

      1. 执行action:zygote 进程就在这里启动

        • for循环去解析参数,根据rc 文件中的action 执行相应操作
      2. 检测并重启需要的进程

      3. 接收子进程的SIGCHLD信号,执行响应的方法

        • 防止子进程成为僵尸进程
  • zygote 层:

    • native 部分:

      • 初始化android 运行时环境(ART),因为Java 代码需要运行在虚拟机中;
      • 初始化 JNI ,因为native 层与 Java 层需要通信
      • 执行ZygoteInit.main 方法,进入Java 部分
    • Java 部分:

      • 创建 socket:实现通信
      • 执行预加载:加快进程的启动速度
      • 通过fork 创建 SystemServer 进程
      • 进入循环:等待AMS 的通知,并根据通知创建对应的进程

SystemServer 进程的创建过程

  • 前情提要:

    • 从ZygoteInit.java 中的main 方法。进入forkSystemServer类;此时,属于Zygote 进程
    • 进程实际上是没有native,java之分的;我们常说Zygote 进程在native 层,SystemServer 进程在Java 层,这可看做一种约定。
  • 第一步:参数赋值

    • 通过字符串数组args 进行赋值:包含uid,gid,nice-name(进程名)
  • 第二步:创建子进程,拿到pid

    • 通过Zygote.forkSystemServer 调用fork(),创建子进程并返回pid

SystemServer 进程的执行过程:

  • 前情提要:

    • 业务需求:需要启动SystemServer.main()

    • 代码入口:进入SystemServer 进程

      if(pid == 0){//此时在SystemServer 进程中
           …………
           return handleSystemServerProcess(parsedArgs);
       }
      

      Java

      Copy

    • handleSystemServerProcess() 通过反射启动SystemServer.main()

      • 源码依据:

        • 先是拿到了ClassLoader,接着调用了ZygoteInit.zygoteInit();

启动Binder线程池和SystemServiceManager

并且启动各种系统服务

SystemServer.main() 初始化SystemServer对象,然后调用run()

new SystemServer().run()

SystemServer.run()

//其他代码省略
 createSystemContext();//加载系统资源
 startBootstrapServices(t);//启动引导服务
 startCoreServices(t);//启动核心服务
 startOtherServices(t);//启动其他服务

SystemServer.createSystemContext()

//系统资源加载 
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();//ContextImpl
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

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

ActivityThread.systemMain()

//ResourcesManager.getInstance()获取资源管理实例
ActivityThread thread = new ActivityThread();

thread.attach(true, 0);
return thread;

thread.attach(true, 0);

mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
/**
getSystemContext()单例模式创建ContextImpl对象mSystemContext-->createSystemContext-->创建LoadedApk对象(创建ApplicationInfo(),创建ClassLoader)
createAppContext()利用刚创建的LoadedApk对象创建新的ContextImpl对象
**/
ContextImpl context = ContextImpl.createAppContext(this,getSystemContext().mPackageInfo);
/**
initializeJavaContextClassLoader() 设置当前的线程ContextClassLoader
newApplication()
public Application newApplication(ClassLoader cl, String className, Context context)throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    //创建Application对象
    Application app = getFactory(context.getPackageName())
        .instantiateApplication(cl, className);
    //将新创建的ContextImpl对象保存到Application父类成员变量mBase
    //将新创建的LoadedApk对象保存到Application的成员变量mLoadedApk
    app.attach(context);
    return app;
    }
**/
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();

SystemServer.startBootstrapServices()

// SystemServiceManager 专门管理各种服务启动(java层各种服务)

ActivityTaskManagerService atm = mSystemServiceManager.startService(
        ActivityTaskManagerService.Lifecycle.class).getService();
        
// 在SystemServiceManager.startService()中new Lifecycle()-->new ActivityManagerService(),且回调Lifecycle.onStart()
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
        mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置AMS的APP安装器
mActivityManagerService.setInstaller(installer);
//开启PMS服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//初始化AMS相关的PMS服务
mActivityManagerService.initPowerManagement();
//添加C/C++各种服务
mActivityManagerService.setSystemProcess();

new ActivityManagerService(context, sAtm) 启动相关服务 创建UI线程 创建ActiveServices 创建CpuTracker线程 Lifecycle.start()

//移除所有的进程组
removeAllProcessGroups();
//启动CpuTracker线程
mProcessCpuThread.start();
//启动电池统计服务
mBatteryStatsService.publish();
//启动APP操作信息服务
mAppOpsService.publish();
//添加到LocalServices中
LocalServices.addService(ActivityManagerInternal.class, mInternal);

ActivityManagerService.setSystemProcess();

/**
ServiceManager c/c++服务

activity AMS
procstats 进程统计
meminfo 内存信息
gfxinfo 图像信息
dbinfo 数据库
cpuinfo 
permission
processinfo 进程信息
cacheinfo 缓存信息
**/
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));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this),
    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
    }
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
ServiceManager.addService("cacheinfo", new CacheBinder(this));
/**
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);
mProfiler = new Profiler();
**/
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
//创建ProcessRecord对象
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                        false,
                        0,
                        new HostingRecord("system"));

ActivityThread.installSystemApplicationInfo(info,getClass().getClassLoader());

//最终调用LoadedApk的installSystemApplicationInfo(),加载名为android的包
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);
//创建用于性能统计Profiler对象
mProfiler = new Profiler();

SystemServer.startOtherServices(t);

//与AMS相关,其他代码省略
/**
安装系统Provider
创建CoreSettingsObserver,用于监控Settings的改变
**/
mActivityManagerService.installSystemProviders();
//
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,new PhoneWindowManager(),mActivityManagerService.mActivityTaskManager);
//加入到底层服务中
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
//WMS管理
mActivityManagerService.setWindowManager(wm);
/**
startSystemUi()启动系统UI
执行一系列服务的systemReady()
**/
mActivityManagerService.systemReady();

//至此80多个服务初始化完成

文末

image

以上就是Android开发技术中比较核心的技术点;SystemServer加载AMS的一些原理及解析;更多Android开发进阶可以查看《Android核心技术手册》里面技术点上千个,能够帮助你在Android开发岗位中深造。

SystemServer中启动服务列表

服务类名称 作用描述 启动模式
EntropyService 提供伪随机数 1.0
PowerManagerService 电源管理服务 1.2/3
ActivityManagerService 最核心的服务之一,管理 Activity 自定义
TelephonyRegistry 通过该服务注册电话模块的事件响应,比如重启、关闭、启动等 1.0
PackageManagerService 程序包管理服务 3.3
AccountManagerService 账户管理服务,是指联系人账户,而不是 Linux 系统的账户 1.0
ContentService ContentProvider 服务,提供跨进程数据交换 3.0
BatteryService 电池管理服务 1.0
LightsService 自然光强度感应传感器服务 1.0
VibratorService 震动器服务 1.0
AlarmManagerService 定时器管理服务,提供定时提醒服务 1.0
WindowManagerService Framework 最核心的服务之一,负责窗口管理 3.3
BluetoothService 蓝牙服务 1.0 +
DevicePolicyManagerService 提供一些系统级别的设置及属性 1.3
StatusBarManagerService 状态栏管理服务 1.3
ClipboardService 系统剪切板服务 1.0
InputMethodManagerService 输入法管理服务 1.0
NetStatService 网络状态服务 1.0
NetworkManagementService 网络管理服务 NMS.create()
ConnectivityService 网络连接管理服务 2.3
ThrottleService 暂不清楚其作用 1.3
AccessibilityManagerService 辅助管理程序截获所有的用户输入,并根据这些输入给用户一些额外的反馈,起到辅助的效果 1.0
MountService 挂载服务,可通过该服务调用 Linux 层面的 mount 程序 1.0
NotificationManagerService 通知栏管理服务, Android 中的通知栏和状态栏在一起,只是界面上前者在左边,后者在右边 1.3
DeviceStorageMonitorService 磁盘空间状态检测服务 1.0
LocationManagerService 地理位置服务 1.3
SearchManagerService 搜索管理服务 1.0
DropBoxManagerService 通过该服务访问 Linux 层面的 Dropbox 程序 1.0
WallpaperManagerService 墙纸管理服务,墙纸不等同于桌面背景,在 View 系统内部,墙纸可以作为任何窗口的背景 1.3
AudioService 音频管理服务 1.0
BackupManagerService 系统备份服务 1.0
AppWidgetService Widget 服务 1.3
RecognitionManagerService 身份识别服务 1.3
DiskStatsService 磁盘统计服务 1.0

推荐阅读更多精彩内容