SystemServer分析记录

文章详细阐述了Android系统中Zygote进程如何forkSystemServer进程,并调用SystemServer的main方法启动一系列关键服务。SystemServer通过SystemServiceManager来管理和启动如ActivityManagerService(AMS)、BatteryService等服务。AMS在SystemServer中被设置为系统服务,并与WindowManagerService(WMS)建立联系,同时启动桌面Launcher。SystemServiceManager负责创建和初始化服务,确保服务按照正确的顺序启动。

Zygote进程forkSystemServer进程后,调用了SystemServer的main方法,具体流程请参考其他资料,这里记录的是SystemServer关键代码的分析

SystemServer代码:

public final class SystemServer {

	private SystemServiceManager mSystemServiceManager;
	private ActivityManagerService mActivityManagerService;
	
	public static void main(String[] args) {
        new SystemServer().run();
    }
	
	private void run() {
		...
		mSystemServiceManager = new SystemServiceManager(mSystemContext);
		...
		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();
        }
		...
	}
	
	private void startBootstrapServices() {
		...
		// AMS服务
		mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
		...
		// 添加AMS到ServiceManager 并添加其他Binder服务
		mActivityManagerService.setSystemProcess();
	}
	
	private void startCoreServices() {
        ...
		// 电池服务
        mSystemServiceManager.startService(BatteryService.class);
		...
    }
	
	private void startOtherServices() {
		...
		// WMS服务
		wm = WindowManagerService.main(context, inputManager,
				mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
				!mFirstBoot, mOnlyCore, new PhoneWindowManager());
		ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
				DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
		...
		// AMS与WMS建立关系
		mActivityManagerService.setWindowManager(wm);
		...
		// 启动桌面Launcher
		mActivityManagerService.systemReady(() -> {
		...
		});
	}

}

主要使用SystemServiceManager启动和管理各种服务:

引导服务作用
Installer系统安装apk时的一个服务类,启动完成Installer服务之后才能启动其他的系统服务
ActivityManagerService负责四大组件的启动、切换、调度。
PowerManagerService计算系统中和Power相关的计算,然后决策系统应该如何反应
LightsService管理和显示背光LED
DisplayManagerService用来管理所有显示设备
UserManagerService多用户模式管理
SensorService为系统提供各种感应器服务
PackageManagerService用来对apk进行安装、解析、删除、卸载等等操作
核心服务
BatteryService管理电池相关的服务
UsageStatsService收集用户使用每一个APP的频率、使用时常
WebViewUpdateServiceWebView更新服务
其他服务
CameraService摄像头相关服务
AlarmManagerService全局定时器管理服务
InputManagerService管理输入事件
WindowManagerService窗口管理服务
VrManagerServiceVR模式管理服务
BluetoothService蓝牙管理服务
NotificationManagerService通知管理服务
DeviceStorageMonitorService存储相关管理服务
LocationManagerService定位管理服务
AudioService音频相关管理服务

SystemServiceManager代码:

public class SystemServiceManager {

	private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

	public SystemService startService(String className) {
		final Class<SystemService> serviceClass;
		try {
			serviceClass = (Class<SystemService>)Class.forName(className);
		} catch (ClassNotFoundException ex) {
			Slog.i(TAG, "Starting " + className);
			throw new RuntimeException("Failed to create service " + className
					+ ": service class not found, usually indicates that the caller should "
					+ "have called PackageManager.hasSystemFeature() to check whether the "
					+ "feature is available on this device before trying to start the "
					+ "services that implement it", ex);
		}
		return startService(serviceClass);
	}

	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);
		}
	}

	public void startService(@NonNull final SystemService service) {
		// 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");
	}
	
}

AMS服务:

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
		
	// SystemServer调用
	// 其他服务都是在start方法添加到ServiceManager
	public void setSystemProcess() {
        try {
			// 添加到ServiceManager
            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));

            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

            synchronized (this) {
                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
                app.persistent = true;
                app.pid = MY_PID;
                app.maxAdj = ProcessList.SYSTEM_ADJ;
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                synchronized (mPidsSelfLocked) {
                    mPidsSelfLocked.put(app.pid, app);
                }
                updateLruProcessLocked(app, false, null);
                updateOomAdjLocked();
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find android system package", e);
        }

        // Start watching app ops after we and the package manager are up and running.
        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 (mAppOpsService.checkOperation(op, uid, packageName)
                                    != AppOpsManager.MODE_ALLOWED) {
                                runInBackgroundDisabled(uid);
                            }
                        }
                    }
                });
    }

	// SystemServer创建WMS后,调用这个方法达成AMS与WMS建立关系
    public void setWindowManager(WindowManagerService wm) {
        synchronized (this) {
            mWindowManager = wm;
            mStackSupervisor.setWindowManager(wm);
            mLockTaskController.setWindowManager(wm);
        }
    }
	
	// 启动Launcher桌面应用
	public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
		...
		startHomeActivityLocked(currentUserId, "systemReady");
		...
	}

	// 所有服务都要继承SystemService,方便SystemServiceManager统一管理
	// 而AMS需要提供给APP使用,需要使用Binder机制,作为服务端继承Stub,所以使用静态内部类持有AMS达到多继承目的
	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();
			// 怎么没有添加到ServiceManager?
		}

		@Override
		public void onBootPhase(int phase) {
			mService.mBootPhase = phase;
			if (phase == PHASE_SYSTEM_SERVICES_READY) {
				mService.mBatteryStatsService.systemServicesReady();
				mService.mServices.systemServicesReady();
			}
		}

		@Override
		public void onCleanupUser(int userId) {
			mService.mBatteryStatsService.onCleanupUser(userId);
		}

		public ActivityManagerService getService() {
			return mService;
		}
	}

}
### Android Framework SystemServer 源码解析与架构分析 #### 1. Zygote 进程启动过程 Zygote 是 Android 系统中的第一个 Java 进程,负责孵化其他应用程序进程。`RuntimeInit.applicationInit()` 方法通过反射机制找到并执行目标类的 `main()` 函数,在此过程中会初始化一些必要的环境变量和配置项[^3]。 ```java protected static Runnable applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { ... return findStaticMain(args.startClass, args.startArgs, classLoader); } ``` 当参数指定为 "com.android.server.SystemServer" 类时,则表示即将启动的是 SystemServer 进程。 #### 2. SystemServer 的创建流程 SystemServer 被视为整个系统的守护者和服务提供者,它运行在一个独立进程中,并承担着启动核心服务的任务。具体来说: - **加载阶段**:读取系统属性文件;设置线程优先级;注册异常处理器。 - **启动阶段**:依次调用各个组件的服务管理器 (Service Manager),如 ActivityManagerService、PackageManagerService 等来完成初始化工作。 - **等待状态**:一旦所有必需的服务都被成功激活之后,进入无限循环监听来自客户端的消息请求直至设备关闭为止。 #### 3. 关键模块介绍 为了更好地理解 SystemServer 所扮演的角色及其内部运作方式,下面列举几个重要的组成部分: ##### a. Service Manager 作为连接不同服务之间的桥梁,Service Manager 提供了一套标准接口用于发布、查找以及绑定远程对象实例。这使得跨进程通信变得简单而高效。 ##### b. Power Manager & Battery Stats 这两个子系统共同协作以优化电量消耗情况,前者主要关注屏幕亮灭控制逻辑,后者则专注于统计电池使用状况并向用户提供反馈建议。 ##### c. Connectivity Services 涵盖了 Wi-Fi、蓝牙、移动数据等多个方面,确保网络连接稳定可靠的同时也支持多模式切换操作。 ##### d. Content Providers 允许应用程序之间共享数据库记录或其他形式的数据集,从而促进了信息交换的安全性和便捷性。 #### 4. 总结 综上所述,SystemServer 不仅是 Android 平台不可或缺的一部分,而且在整个生态系统内占据着举足轻重的地位。通过对上述知识点的学习可以加深开发者对于底层工作机制的认识程度,进而有助于构建更加健壮的应用程序[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值