在之前的Android SystemServer启动(二)中,分析到在
今天我们就来了解一下
启动AMS
在三大分类服务的启动服务中,即
private void startBootstrapServices() { ... ActivityTaskManagerService atm = mSystemServiceManager.startService( ActivityTaskManagerService.Lifecycle.class).getService(); mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); ... }
public static final class Lifecycle extends SystemService { private final ActivityManagerService mService; private static ActivityTaskManagerService sAtm; public Lifecycle(Context context) { super(context); mService = new ActivityManagerService(context, sAtm); } public static ActivityManagerService startService( SystemServiceManager ssm, ActivityTaskManagerService atm) { sAtm = atm; return ssm.startService(ActivityManagerService.Lifecycle.class).getService(); } @Override public void onStart() { mService.start(); } ... }
内部是通过反射来创建
所以接下来我们来看下
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) { ... // 创建名为ActivityManager的线程,并创建MainHandler // 处理各种状态信息的线程(GC、service_timeout、update_time_zone、kill_application、kill_zygote) mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); mHandlerThread.start(); mHandler = new MainHandler(mHandlerThread.getLooper()); // 获取UiHandler mUiHandler = mInjector.getUiHandler(this); // 创建与启动proc线程 mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false /* allowIo */); mProcStartHandlerThread.start(); mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper()); // 定义一些常量,管理ActivityManager的行为 mConstants = new ActivityManagerConstants(mContext, this, mHandler); // 追踪活跃的uid final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */); mProcessList.init(this, activeUids); // 低内存探测器 mLowMemDetector = new LowMemDetector(this); mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids); // 前台广播接收器 final BroadcastConstants foreConstants = new BroadcastConstants( Settings.Global.BROADCAST_FG_CONSTANTS); foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT; // 后台广播接收器 final BroadcastConstants backConstants = new BroadcastConstants( Settings.Global.BROADCAST_BG_CONSTANTS); backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; // 卸载广播接收器 final BroadcastConstants offloadConstants = new BroadcastConstants( Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT; offloadConstants.SLOW_TIME = Integer.MAX_VALUE; mEnableOffloadQueue = SystemProperties.getBoolean( "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false); mFgBroadcastQueue = new BroadcastQueue(this, mHandler, "foreground", foreConstants, false); mBgBroadcastQueue = new BroadcastQueue(this, mHandler, "background", backConstants, true); mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler, "offload", offloadConstants, true); mBroadcastQueues[0] = mFgBroadcastQueue; mBroadcastQueues[1] = mBgBroadcastQueue; mBroadcastQueues[2] = mOffloadBroadcastQueue; mServices = new ActiveServices(this); mProviderMap = new ProviderMap(this); mPackageWatchdog = PackageWatchdog.getInstance(mUiContext); mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog); final File systemDir = SystemServiceManager.ensureSystemDir(); // 电池状态 mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, BackgroundThread.get().getHandler()); mBatteryStatsService.getActiveStatistics().readLocked(); mBatteryStatsService.scheduleWriteToDisk(); mOnBattery = DEBUG_POWER ? true : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); mBatteryStatsService.getActiveStatistics().setCallback(this); mOomAdjProfiler.batteryPowerChanged(mOnBattery); // 进程状态 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler); ... mActivityTaskManager = atm; mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper()); mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class); // 进程cpu统计线程 mProcessCpuThread = new Thread("CpuTracker") { @Override public void run() { synchronized (mProcessCpuTracker) { mProcessCpuInitLatch.countDown(); mProcessCpuTracker.init(); } while (true) { try { try { synchronized(this) { final long now = SystemClock.uptimeMillis(); long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; //Slog.i(TAG, "Cpu delay=" + nextCpuDelay // + ", write delay=" + nextWriteDelay); if (nextWriteDelay < nextCpuDelay) { nextCpuDelay = nextWriteDelay; } if (nextCpuDelay > 0) { mProcessCpuMutexFree.set(true); this.wait(nextCpuDelay); } } } catch (InterruptedException e) { } // 更新cpu的信息 updateCpuStatsNow(); } catch (Exception e) { Slog.e(TAG, "Unexpected exception collecting process stats", e); } } } }; ... }
所以这里主要做的事是创建
创建完
private void start() { // 移除所有进程组 removeAllProcessGroups(); // 开启进程cpu统计线程 mProcessCpuThread.start(); // 启动电池统计服务 mBatteryStatsService.publish(); mAppOpsService.publish(mContext); // 添加到本地LocalServices中 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); mActivityTaskManager.onActivityManagerInternalAdded(); mUgmInternal.onActivityManagerInternalAdded(); mPendingIntentController.onActivityManagerInternalAdded(); try { // 等待进程cpu统计线程运行 mProcessCpuInitLatch.await(); } catch (InterruptedException e) { Slog.wtf(TAG, "Interrupted wait during start", e); Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted wait during start"); } }
这个时候
下面我们在来看下
startBootstrapServices
private void startBootstrapServices() { ... mActivityManagerService.initPowerManagement(); ... mActivityManagerService.setSystemProcess(); ... }
initPowerManagement
首先会初始化
public void initPowerManagement() { mActivityTaskManager.onInitPowerManagement(); mBatteryStatsService.initPowerManagement(); mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); }
最终会通过
setSystemProcess
接下来是
public void setSystemProcess() { try { // 注册ActivityManagerService ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); // 注册 ProcessStatsService ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); // 注册MemBinder ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_HIGH); // 注册GraphicsBinder ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); // 注册DbBinder ServiceManager.addService("dbinfo", new DbBinder(this)); if (MONITOR_CPU_USAGE) { // 注册CpuBinder ServiceManager.addService("cpuinfo", new CpuBinder(this), /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); } // 注册PermissionController ServiceManager.addService("permission", new PermissionController(this)); // 注册ProcessInfoService ServiceManager.addService("processinfo", new ProcessInfoService(this)); // 加载包名为android的包,最终通过LoadedApk来加载 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); ... }
需要注意的是,这里将
接下来就进入了
startCoreServices
private void startCoreServices() { ... mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); ... }
这里做的事情很简单,设置
startOtherServices
继续来到启动其它的服务模块
private void startOtherServices() { ... mActivityManagerService.installSystemProviders(); mActivityManagerService.setWindowManager(wm); mActivityManagerService.systemReady(...) ... }
在这里主要做的是安装系统的
installSystemProviders
public final void installSystemProviders() { List<ProviderInfo> providers; synchronized (this) { ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID); // 获取Providers providers = generateApplicationProvidersLocked(app); if (providers != null) { for (int i=providers.size()-1; i>=0; i--) { ProviderInfo pi = (ProviderInfo)providers.get(i); // 清除非系统的Providers if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { providers.remove(i); } } } } // 通过ActivityThread来安装系统的Providers if (providers != null) { mSystemThread.installSystemProviders(providers); } synchronized (this) { mSystemProvidersInstalled = true; } mConstants.start(mContext.getContentResolver()); mCoreSettingsObserver = new CoreSettingsObserver(this); mActivityTaskManager.installSystemProviders(); mDevelopmentSettingsObserver = new DevelopmentSettingsObserver(); SettingsToPropertiesMapper.start(mContext.getContentResolver()); mOomAdjuster.initSettings(); }
这里主要做的就是安装系统的
WindowManagerService
public void setWindowManager(WindowManagerService wm) { synchronized (this) { mWindowManager = wm; mActivityTaskManager.setWindowManager(wm); } }
设置
systemReady
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) { goingCallback before if (goingCallback != null) goingCallback.run(); goingCallback after }
在调用
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) { synchronized(this) { // 第一次进来为false,跳过 if (mSystemReady) { if (goingCallback != null) { goingCallback.run(); } return; } ... mSystemReady = true; } ... ArrayList<ProcessRecord> procsToKill = null; synchronized(mPidsSelfLocked) { for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { ProcessRecord proc = mPidsSelfLocked.valueAt(i); // 非president进程 if (!isAllowedWhileBooting(proc.info)){ if (procsToKill == null) { procsToKill = new ArrayList<ProcessRecord>(); } // 加入到procsTokill中 procsToKill.add(proc); } } } synchronized(this) { if (procsToKill != null) { // kill procsToKill中的进程 for (int i=procsToKill.size()-1; i>=0; i--) { ProcessRecord proc = procsToKill.get(i); mProcessList.removeProcessLocked(proc, true, false, "system update done"); } } mProcessesReady = true; } ... if (goingCallback != null) goingCallback.run(); ... }
主要做的事情杀掉
之后再调用
mActivityManagerService.systemReady(() -> { // BootPhase 550 mSystemServiceManager.startBootPhase( SystemService.PHASE_ACTIVITY_MANAGER_READY); try { mActivityManagerService.startObservingNativeCrashes(); } catch (Throwable e) { reportWtf("observing native crashes", e); } traceBeginAndSlog("MakeConnectivityServiceReady"); try { if (connectivityF != null) { connectivityF.systemReady(); } } catch (Throwable e) { reportWtf("making Connectivity Service ready", e); } ... // BootPhase 600 mSystemServiceManager.startBootPhase( SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); try { if (locationF != null) { locationF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying Location Service running", e); } try { if (countryDetectorF != null) { countryDetectorF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying CountryDetectorService running", e); } ... }, BOOT_TIMINGS_TRACE_LOG);
这个在Android SystemServer启动(二)中已经分析了,这里就不多介绍了。
主要是对一些服务进行
最后来到
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) { ... if (goingCallback != null) goingCallback.run(); final int currentUserId = mUserController.getCurrentUserId(); if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) { throw new RuntimeException("System user not started while current user is:" + currentUserId); } mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, Integer.toString(currentUserId), currentUserId); mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, Integer.toString(currentUserId), currentUserId); // 调用所有SystemService的onStartUser方法 mSystemServiceManager.startUser(currentUserId); synchronized (this) { // 开启Persistent app startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE); mBooting = true; if (UserManager.isSplitSystemUser() && Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) { ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class); try { AppGlobals.getPackageManager().setComponentEnabledSetting(cName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0, UserHandle.USER_SYSTEM); } catch (RemoteException e) { throw e.rethrowAsRuntimeException(); } } // 启动系统桌面Activity mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady"); mAtmInternal.showSystemReadyErrorDialogsIfNeeded(); final int callingUid = Binder.getCallingUid(); final int callingPid = Binder.getCallingPid(); long ident = Binder.clearCallingIdentity(); try { // 发送USER_STARTED广播 Intent intent = new Intent(Intent.ACTION_USER_STARTED); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid, currentUserId); // 发送USER_STARTING广播 intent = new Intent(Intent.ACTION_USER_STARTING); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId); broadcastIntentLocked(null, null, intent, null, new IIntentReceiver.Stub() { @Override public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) throws RemoteException { } }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, OP_NONE, null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid, UserHandle.USER_ALL); } catch (Throwable t) { Slog.wtf(TAG, "Failed sending first user broadcasts", t); } finally { Binder.restoreCallingIdentity(ident); } mAtmInternal.resumeTopActivities(false /* scheduleIdle */); mUserController.sendUserSwitchBroadcasts(-1, currentUserId); BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK, BINDER_PROXY_LOW_WATERMARK); BinderInternal.nSetBinderProxyCountEnabled(true); BinderInternal.setBinderProxyCountCallback( new BinderInternal.BinderProxyLimitListener() { @Override public void onLimitReached(int uid) { Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid " + Process.myUid()); BinderProxy.dumpProxyDebugInfo(); if (uid == Process.SYSTEM_UID) { Slog.i(TAG, "Skipping kill (uid is SYSTEM)"); } else { killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid), "Too many Binders sent to SYSTEM"); } } }, mHandler); // 恢复栈顶Activity mAtmInternal.resumeTopActivities(false /* scheduleIdle */); // 发送User_SWITCH 广播 mUserController.sendUserSwitchBroadcasts(-1, currentUserId); ... } }
其中
public void startUser(final int userHandle) { final int serviceLen = mServices.size(); // 遍历mServices for (int i = 0; i < serviceLen; i++) { final SystemService service = mServices.get(i); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "onStartUser " + service.getClass().getName()); long time = SystemClock.elapsedRealtime(); try { // 回调onStartUser service.onStartUser(userHandle); } catch (Exception ex) { Slog.wtf(TAG, "Failure reporting start of user " + userHandle + " to service " + service.getClass().getName(), ex); } } }
boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting, boolean fromHomeKey) { if (displayId == INVALID_DISPLAY) { displayId = getTopDisplayFocusedStack().mDisplayId; } Intent homeIntent = null; ActivityInfo aInfo = null; if (displayId == DEFAULT_DISPLAY) { homeIntent = mService.getHomeIntent(); aInfo = resolveHomeActivity(userId, homeIntent); } else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) { Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, displayId); aInfo = info.first; homeIntent = info.second; } if (aInfo == null || homeIntent == null) { return false; } if (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) { return false; } // 设置home Intent 的Component信息 homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name)); homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK); // 设置extra if (fromHomeKey) { homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true); } final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId( aInfo.applicationInfo.uid) + ":" + displayId; // 启动桌面Activity mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason, displayId); return true; }
总结一下,在
- 调用所有之前添加的
SystemService 的onStartUser 方法 - 启动
Persistent 进程 - 启动系统桌面Activity
- 发送USER_STARTED广播
- 发送USER_STARTING广播
- 恢复栈顶Activity
- 发送User_SWITCH广播
以上就是
整个过程主要做的事情是:
- 通过
Lifecycle 创建AMS 实例,同时调用onStart() 方法启动AMS - 通过
setSystemProcess 注册AMS 、meminfo 、gfxinfo 、dbinfo 、cpuinfo 等服务到ServiceManager 中 - 通过
installSystemProviders 来加载系统的providers - 通过
systemReady 来ready 与running 各种服务,同时启动桌面应用,发送相关广播与恢复栈顶Activity
最后
如果你看到了这里,觉得文章写得不错就给个赞呗?
更多Android进阶指南 可以扫码 解锁 《Android十大板块文档》
1.Android车载应用开发系统学习指南(附项目实战)
2.Android Framework学习指南,助力成为系统级开发高手
3.2023最新Android中高级面试题汇总+解析,告别零offer
4.企业级Android音视频开发学习路线+项目实战(附源码)
5.Android Jetpack从入门到精通,构建高质量UI界面
6.Flutter技术解析与实战,跨平台首要之选
7.Kotlin从入门到实战,全方面提升架构基础
8.高级Android插件化与组件化(含实战教程和源码)
9.Android 性能优化实战+360°全方面性能调优
10.Android零基础入门到精通,高手进阶之路
敲代码不易,关注一下吧。?( ′???` ) ??