开始进入Framework的源码分析,在分析源码之前,先来了解一下android系统启动的流程,如下图所示:
在Zygote进程中会孵化一个SystemServer进程,在这个SystemServer进程中完成了大量的系统服务的启动,这些系统服务启动完成后才启动桌面Launcher进程,那么这个SystemServer又是怎么启动的。
SystemServer的启动由于需要启动大量的系统服务,所以每次开机都需要耗时较长才会显示桌面。
启动过程:
在进入源码分析之前,先来根据下面的思维导图了解一下整体流程,按照执行顺序进行了排序。
1、准备主线程Looper
说明:
1、SystemServer的启动从其Main方法执行;创建SystemServer实例调用其run方法;
2、配置系统时间、时区、语言等信息;
3、准备主线程Looper
//SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
try {
// Record the process start information in sys props.
SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//
// Default the timezone property to GMT if not set.
//设置时间
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
// If the system has "persist.sys.language" and friends set, replace them with
// "persist.sys.locale". Note that the default locale at this point is calculated
// using the "-Duser.locale" command line flag. That flag is usually populated by
// AndroidRuntime using the same set of system properties, but only the system_server
// and system apps are allowed to set them.
//
// NOTE: Most changes made here will need an equivalent change to
// core/jni/AndroidRuntime.cpp
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
PackageItemInfo.forceSafeLabels();
// Default to FULL within the system server.
SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
SQLiteCompatibilityWalFlags.init(null);
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
int uptimeMillis = (int) SystemClock.elapsedRealtime();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
}
// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can | xq oqi't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// Within the system server, when parceling exceptions, include the stack trace
Parcel.setStackTraceParceling(true);
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
//这里开始准备主线程的Looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// Initialize native services.
System.loadLibrary("android_servers");
// Debug builds - allow heap profiling.
if (Build.IS_DEBUGGABLE) {
initZygoteChildHeapProfiling();
}
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
2、加载nativeService:
// Initialize native services.
System.loadLibrary("android_servers");
3、创建systemContext
- 创建ActivityThread实例;
- 获取systemContext、systemUiContext;
- 设置系统theme
// Initialize the system context.
createSystemContext();
private void createSystemContext() {
//创建ActivityThread
ActivityThread activityThread = ActivityThread.systemMain();
//获取systemContext,并设置theme
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//获取systemUiContenx ,设置theme
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
3.1 创建ActivityThread
//ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
public static ActivityThread systemMain() {
// The system process on low-memory devices do not get to use hardware
// accelerated drawing, since this can add too much overhead to the process.
if (!ActivityManager.isHighEndGfx()) {
ThreadedRenderer.disable(true);
} else {
ThreadedRenderer.enableForegroundTrimming();
}
//1.这里new一个ActivityThread出来,通过构造方法可以明白是获得了资源管理器实例
ActivityThread thread = new ActivityThread();
//2.这里的attach第一个参数是true,
thread.attach(true, 0);
return thread;
}
//构造方法
ActivityThread() {
mResourcesManager = ResourcesManager.getInstance();
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
//注意由于第一个参数这时传递进来的true ,所以不会进入该分支
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
//1.1 创建Instrumentation队列,并将当前的ActivityThead赋值给instrumentation的成员变量
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//1.2 创建app上下文
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
//1.3
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
//..........
}
//1.2.1 获取systemContext
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
//1.2.1.1 创建systemContext
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
}
//ContextImpl.java
class ContextImpl extends Context {
//1.2.1.2创建systemContext
static ContextImpl createSystemContext(ActivityThread mainThread) {
//1.2.1.2.1进入LoadedApk的构造方法:创建applicationInfo,系统资源、类加载器等
LoadedApk packageInfo = new LoadedApk(mainThread);
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null, null);
//1.2.1.2.2 给context设置资源
context.setResources(packageInfo.getResources());
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
@NonNull LoadedApk packageInfo, @Nullable String splitName,
@Nullable IBinder activityToken, @Nullable UserHandle user, int flags,
@Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) {
mOuterContext = this;
// If creator didn't specify which storage to use, use the default
// location for application.
if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
| Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
final File dataDir = packageInfo.getDataDirFile();
if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) {
flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
} else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) {
flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
}
}
mMainThread = mainThread;
mActivityToken = activityToken;
mFlags = flags;
if (user == null) {
user = Process.myUserHandle();
}
mUser = user;
mPackageInfo = packageInfo;
mSplitName = splitName;
mClassLoader = classLoader;
mResourcesManager = ResourcesManager.getInstance();
String opPackageName;
if (container != null) {
mBasePackageName = container.mBasePackageName;
opPackageName = container.mOpPackageName;
setResources(container.mResources);
mDisplay = container.mDisplay;
} else {
mBasePackageName = packageInfo.mPackageName;
ApplicationInfo ainfo = packageInfo.getApplicationInfo();
if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
// Special case: system components allow themselves to be loaded in to other
// processes. For purposes of app ops, we must then consider the context as
// belonging to the package of this process, not the system itself, otherwise
// the package+uid verifications in app ops will fail.
opPackageName = ActivityThread.currentPackageName();
} else {
opPackageName = mBasePackageName;
}
}
mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName;
mContentResolver = new ApplicationContentResolver(this, mainThread);
}
//1.2.2 创建app上线文
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
String opPackageName) {
if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
//1.2.2.1
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null, opPackageName);
context.setResources(packageInfo.getResources());
return context;
}
}
//LoadedApk.java
public final class LoadedApk {
LoadedApk(ActivityThread activityThread) {
mActivityThread = activityThread;
mApplicationInfo = new ApplicationInfo();
mApplicationInfo.packageName = "android";
mPackageName = "android";
mAppDir = null;
mResDir = null;
mSplitAppDirs = null;
mSplitResDirs = null;
mSplitClassLoaderNames = null;
mOverlayDirs = null;
mDataDir = null;
mDataDirFile = null;
mDeviceProtectedDataDirFile = null;
mCredentialProtectedDataDirFile = null;
mLibDir = null;
mBaseClassLoader = null;
mSecurityViolation = false;
mIncludeCode = true;
mRegisterPackage = false;
mResources = Resources.getSystem();
mDefaultClassLoader = ClassLoader.getSystemClassLoader();
mAppComponentFactory = createAppFactory(mApplicationInfo, mDefaultClassLoader);
mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
new ApplicationInfo(mApplicationInfo));
}
//1.3.1
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"initializeJavaContextClassLoader");
initializeJavaContextClassLoader();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
//1.3.1.1
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
try {
//1.3.1.2
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!instrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
return app;
}
}
3.2 getSystemContext()
这一部分其实和3.1中获取systemContext是一样的步骤,这里就不在啰嗦了。
4、创建systemServiceManager,准备线程池初始化任务
//SystemServer.java
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
SystemServerInitThreadPool.start();
5、启动服务
5.1、启动引导服务
引导服务主要有常见的:看门狗、AMS ,installer安装器、PKMS应用包管理器,电量管理PMS等引导服务,详细细节看下面的源码:
注:下面的源码笔者进行了删减,仅保留了一些常见的服务及其执行的顺序
//SystemServer.java
//这里是启动引导服务
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
/**
启动watchDog
首先启动看门狗,是为了在引导服务期间发生死锁时是系统服务奔溃
*/
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
/**
>>>>>>>>创建安装器installer ,用于PKMS安装应用程序使用
*/
Installer installer = mSystemServiceManager.startService(Installer.class);
// AMS创建启动
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
//PMS 电量管理服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//命令终端管理器
mSystemServiceManager.startService(ThermalManagerService.class);
//初始化电量管理PowerManager
mActivityManagerService.initPowerManagement();
// Manages LEDs and display backlight so we need it to bring up the display.
mSystemServiceManager.startService(LightsService.class);
//显示管理器需要在包管理器启动之前提供显示指标
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// 启动显示管理器
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
//启动PKMS
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
// 现在包管理器已经启动,请注册dex load reporter以捕获任何系统服务器加载的dex文件。
// 这些dex文件将由BackgroundDexOptService进行优化。
SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService);
mPackageManager = mSystemContext.getPackageManager();
// 初始化用于缓存包中资源的属性缓存。
AttributeCache.init(mSystemContext);
// 为系统进程设置应用程序实例并开始。
mActivityManagerService.setSystemProcess();
//看门狗的设置
watchdog.init(mSystemContext, mActivityManagerService);
// 初始化:管理覆盖包服务
mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
}
5.2、启动核心服务
//SystemServer.java
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
// 初始化系统配置服务
mSystemServiceManager.startService(SystemConfigService.class);
// 初始化灯光服务,获取电池电量等
mSystemServiceManager.startService(BatteryService.class);
// 启动应用程序使用统计信息服务
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));
// 跟踪可更新WebView是否处于就绪状态,并监视更新安装。
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
//跟踪并缓存设备状态。
mSystemServiceManager.startService(CachedDeviceStateService.class);
// 跟踪在Binder调用中花费的cpu时间
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
//跟踪处理程序中处理消息所花费的时间。.
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
//管理apk回滚
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
// 用于捕获错误报告的服务.
mSystemServiceManager.startService(BugreportManagerService.class);
//GPU和GPU驱动程序的服务
mSystemServiceManager.startService(GpuService.class);
}
5.3、启动其他服务
在这个其他服务中包含了很多我们需要使用到的服务,本文下面仅列出一部分常见的服务,更多细节见源码
//SystemServer.java
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
try {
mActivityManagerService.installSystemProviders();
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
mSystemServiceManager.startService(new AlarmManagerService(context));
inputManager = new InputManagerService(context);
// WMS(Window Manager Service)启动过程
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);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
//给AMS设置WindowManagerService
mActivityManagerService.setWindowManager(wm);
//wms 初始化
wm.onInitReady();
if (!isWatch && enableVrService) {
//VR管理服务
mSystemServiceManager.startService(VrManagerService.class);
}
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
inputManager.start();
// TODO: Use service dependencies instead.
mDisplayManagerService.windowManagerAndInputReady();
if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
} else if (!context.getPackageManager().hasSystemFeature
(PackageManager.FEATURE_BLUETOOTH)) {
} else {
//启动蓝牙服务
mSystemServiceManager.startService(BluetoothService.class);
}
} catch (Throwable e) {
throw e;
}
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!isWatch) {
try {
//状态栏管理服务
statusBar = new StatusBarManagerService(context);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
} catch (Throwable e) {
}
}
try {
//网络管理服务
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
reportWtf("starting NetworkManagement Service", e);
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI)) {
//Wifi相关的服务:扫描wifi
mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
mSystemServiceManager.startService(
"com.android.server.wifi.scanner.WifiScanningService");
}
//状态栏的通知服务
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.removeDeprecated(context);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
//定位管理服务
mSystemServiceManager.startService(LocationManagerService.Lifecycle.class);
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
//桌面壁纸管理服务
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
|| mPackageManager.hasSystemFeature(
PackageManager.FEATURE_USB_ACCESSORY)
|| isEmulator) {
// USB服务
mSystemServiceManager.startService(USB_SERVICE_CLASS);
}
// TODO(aml-jobscheduler): Think about how to do it properly.
//JobScheduler
mSystemServiceManager.startService(JOB_SCHEDULER_SERVICE_CLASS);
try {
//runtime服务
ServiceManager.addService("runtime", new RuntimeService(context));
} catch (Throwable e) {
reportWtf("starting RuntimeService", e);
}
if (hasFeatureFace) {
//人脸识别的服务
mSystemServiceManager.startService(FaceService.class);
}
}
if (!disableCameraService) {
//相机服务代理
mSystemServiceManager.startService(CameraServiceProxy.class);
}
// Permission policy service
//权限管理策略服务
mSystemServiceManager.startService(PermissionPolicyService.class);
}
6、Looper开始工作
SystemServer在run中执行启动一些列服务后,最后启动Looper进入Handler的消息永动机中开始工作。关于Handler另作分析。
总结:
通过上述源码分析,我们可以清楚的知道,SystemServer的启动过程:
准备主线程的Looper ,
加载NativeSystem ,加载好之后创建SystemContext提供经常允许的环境等;
创建SystemServiceManager,并准备线程池来进行初始化任务;
创建并启动一系列的服务(引导服务,核心服务,其他服务)
最后Looper永动机开始工作,这样SystemServer就启动完成了。
ActivityThread的创建过程,需要特别注意,而且非常重要。
在上面的源码中,我们可以看到大部分的服务是通过SystemServerManager来启动的,那么要详情了解具体一个Server的启动就要从SystemServerManager的startService()开始了。