SystemServer分析记录

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

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SystemServerAndroid 系统启动过程中的关键组件之一,它负责启动和管理系统中的各种服务和进程。SystemServer 的主要功能如下: 1. 启动 Android 系统中的各种系统服务,如 ActivityManagerService、PackageManagerService、WindowManagerService 等; 2. 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程; 3. 启动系统中的各种进程,如系统进程、系统应用进程等; 4. 加载和初始化 Android 系统的各种服务和组件。 下面是 SystemServer 的源码解析: 1. SystemServer 的入口 SystemServer 的入口在 frameworks/base/services/java/com/android/server/SystemServer.java 文件中。在该文件中,SystemServer 类继承了 Binder 和 Runnable 接口,并且实现了 Runnable 接口的 run() 方法,该方法是 SystemServer 的入口。 在 run() 方法中,SystemServer 执行了以下操作: 1.1. 初始化 SystemServer 的环境 SystemServer 首先初始化自己的环境,包括设置系统属性、设置线程优先级等。 1.2. 启动各种系统服务 SystemServer 启动 Android 系统中的各种系统服务,包括 ActivityManagerService、PackageManagerService、WindowManagerService 等。这些服务都是在 SystemServer 的构造方法中创建的。 1.3. 初始化和启动 Zygote 进程 SystemServer 初始化和启动 Zygote 进程,该进程将作为应用程序进程的父进程。具体而言,SystemServer 调用 Zygote 的 main() 方法启动 Zygote 进程,并且设置 Zygote 的命令行参数。 1.4. 启动系统中的各种进程 SystemServer 启动 Android 系统中的各种进程,包括系统进程、系统应用进程等。具体而言,SystemServer 调用 ActivityManagerService 的 startSystemServer() 方法启动系统进程,并且调用 PackageManagerService 的 scanDirTracedLI() 方法扫描系统应用。 1.5. 加载和初始化 Android 系统的各种服务和组件 SystemServer 加载和初始化 Android 系统的各种服务和组件,包括 SystemUI、Launcher、InputMethodService 等。具体而言,SystemServer 调用 ActivityManagerService 的 startHomeActivity() 方法启动 Launcher,并且调用 PackageManagerService 的 packageInstalled() 方法加载和初始化应用程序。 2. SystemServer启动流程 SystemServer启动流程如下: 2.1. 启动 init 进程 在 Android 系统启动过程中,init 进程是第一个进程。init 进程启动时,会执行 init.rc 脚本中的命令,并且启动 SystemServer 进程。 2.2. 创建 SystemServer 进程 SystemServer 进程是在 init.rc 脚本中通过 service 命令创建的。具体而言,init.rc 脚本中会执行以下命令: ``` service system_server /system/bin/app_process -Xbootclasspath:/system/framework/core-libart.jar:/system/framework/conscrypt.jar:/system/framework/okhttp.jar:/system/framework/bouncycastle.jar:/system/framework/apache-xml.jar:/system/framework/core-junit.jar -classpath /system/framework/services.jar com.android.server.SystemServer ``` 该命令会启动 SystemServer 进程,并且设置 SystemServer 的启动参数。 2.3. 执行 SystemServer 的 run() 方法 当 SystemServer 进程启动后,会执行 SystemServer 的 run() 方法。在 run() 方法中,SystemServer 完成了 Android 系统的初始化和启动过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值