接着上篇文章看起:Android 系统启动过程-Zygote启动
基于Android10源码分析:
概述
ActivityManagerService(简称AMS),它作为一个系统服务管理着Activity、Service、ContentProvider和BroadcastReceiver这四大组件的启动,可以说AMS服务对于Android系统来讲十分的重要。文章将从AMS的启动和AMS如何管理Activity的启动这两方面来分析AMS在Android体系中所发挥的作用。
AMS相关目录结构
AMS代码主要在下面几个目录(AndroidQ上AMS相关部分功能移到了wm下):
frameworks/base/core/java/android/app/
frameworks/base/services/core/java/com/android/server/am/
frameworks/base/services/core/java/com/android/server/wm/
下面具体看下几个重要文件
frameworks/base/core/java/android/app/下:
Activity.java:所有Activity的父类。
ActivityManager.java:AMS的客户端,提供给用户可调用的api。
ActivityThread.java:应用进程的主线程类,一般即UI线程。
frameworks/base/services/core/java/com/android/server/am/下:
ActiveServices.java:控制service的启动、重启等。
ProcessRecord.java:记录每个进程的信息。
frameworks/base/services/core/java/com/android/server/wm/下:
ActivityRecord.java:activity对象信息的记录。
ActivityStack.java/ActivityStackSupervisor.java:管理activity生命周期及堆栈等。
TaskRecord.java:任务栈记录,管理一个任务的应用activity
ActivityTaskManagerService.java/ActivityTaskManagerInternal.java:管理activity的启动和调度。
文末附上了一个图片,是ActivityStack、ActivityStackSupervisor、TaskRecord、ActivityRecord、ProcessRecord之间的关系。
一、AMS的启动
首先AMS的启动是在SystemServer中完成的,SystemServer负责启动各种各样的系统服务,这里就包括ActivityManagerService。
源码位置:/frameworks/base/services/java/com/android/server/SystemServer.java
SystemServer的run()中,有
startBootstrapServices();
startCoreServices();
startOtherServices();
先看下startBootstrapServices方法:
private void startBootstrapServices() {
// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
// TODO: Might need to move after migration to WM.
//启动ATMS
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//启动AMS
mActivityManagerService =
ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//将SystemServer.java中创建的对象mSystemServiceManager 设置到了AMS中
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//将SystemServer.java中创建的Installer对象installer设置到AMS中
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
traceEnd();
// Set up the Application instance for the system process and get started.
traceBeginAndSlog("SetSystemProcess");
//setSystemProcess方法最核心的一点就是将AMS注册到ServiceManager中,后面解释
mActivityManagerService.setSystemProcess();
traceEnd();
}
1.1 先看ATMS的启动
ActivityTaskManagerService是Android 10新引入的变化,也是系统服务,用来管理Activity启动和调度,包括其容器(task、stacks、displays等)。
Android 10将原先AMS中对activity的管理和调度移到了ActivityTaskManagerService中,位置放到了wm下(见上面完整路径),因此AMS负责四大组件中另外3个(service, broadcast, contentprovider)的管理和调度。
首先看下
mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class)这行代码,
是调用了系统服务管理器SystemServiceManager的startService方法,在此以启动ATMS为例说明:
源码位置/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
/**
* 例如:传递参数className=ActivityTaskManagerService.Lifecycle.class
*/
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
//得到ActivityTaskManagerService.Lifecycle的class文件
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);
}
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
//上面传递的name=ActivityTaskManagerService.Lifecycle
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 {
//上例:调用ActivityTaskManagerService.Lifecycle的onStart()方法
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");
}
接着分析ActivityTaskManagerService.Lifecycle的onStart方法:
/**
* ActivityTaskManagerService的内部类Lifecycle
*/
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
/**
* 调用onStart()方法
*/
@Override
public void onStart() {
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
@Override
public void onUnlockUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.onUserUnlocked(userId);
}
}
@Override
public void onCleanupUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
}
}
public ActivityTaskManagerService getService() {
return mService;
}
}
其中publishBinderService方法是将ActivityTaskManagerService加入到ServiceManager中
protected final void publishBinderService(String name, IBinder service) {
publishBinderService(name, service, false);
}
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated) {
publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
}
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
接着调用ActivityTaskManagerService的start()方法:
final ActivityTaskManagerInternal mInternal;
public ActivityTaskManagerService(Context context) {
mContext = context;
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
mLifecycleManager = new ClientLifecycleManager();
//构造方法中初始化了LocalService
mInternal = new LocalService();
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
}
/**
* start()方法
*/
private void start() {
//mInternal在上面的定义, mInternal = new LocalService();
//其中LocalService是ActivityTaskManagerService的内部类
//LocalServices的addService方法就是将ActivityTaskManagerService.LocalService放到其内部风中的map集合中,看后面代码
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
简单看下ActivityTaskManagerService的内部类LocalService:
/**
* ActivityTaskManagerService的内部类LocalService,继承ActivityTaskManagerInternal,
* 内部的方法实际上是对ActivityTaskManagerService的封装
*/
final class LocalService extends ActivityTaskManagerInternal {
......
@Override
public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
Intent intent, Bundle options, int userId) {
return ActivityTaskManagerService.this.startActivityAsUser(
caller, callerPacakge, intent,
intent.resolveTypeIfNeeded(mContext.getContentResolver()),
null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
false /*validateIncomingUser*/);
}
......
}
看下/frameworks/base/core/java/com/android/server/LocalServices.java这个类,(这个类就是将各个service存放到内部的map集合中)
public final class LocalServices {
private LocalServices() {}
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
/**
* Returns a local service instance that implements the specified interface.
*
* @param type The type of service.
* @return The service object.
*/
/**
* 获取服务类
*/
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
synchronized (sLocalServiceObjects) {
return (T) sLocalServiceObjects.get(type);
}
}
/**
* Adds a service instance of the specified interface to the global registry of local services.
*/
public static <T> void addService(Class<T> type, T service) {
synchronized (sLocalServiceObjects) {
if (sLocalServiceObjects.containsKey(type)) {
throw new IllegalStateException("Overriding service registration");
}
//定义的<key, value> --> <ActivityManagerService.LocalService.class, ActivityManagerService.LocalService对象>
sLocalServiceObjects.put(type, service);
}
}
/**
* Remove a service instance, must be only used in tests.
*/
@VisibleForTesting
public static <T> void removeServiceForTest(Class<T> type) {
synchronized (sLocalServiceObjects) {
sLocalServiceObjects.remove(type);
}
}
}
1.2 接着看AMS的启动
同理ATMS启动过程,
mActivityManagerService =
ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
直接看代码流程,源码位置:/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
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() {
//调用ActivityManagerService的start()方法
mService.start();
}
......
public ActivityManagerService getService() {
return mService;
}
}
接着调用ActivityManagerService 的start()方法:
/**
* start()主要:
* 移除所有进程组,复位进程后,启动CPU监控线程。mProcessCpuThread在前面构造函数中创建的线程。
* 注册电池、权限管理的相关服务
* LocalService只能本进程使用,不可跨进程。
*/
private void start() {
//移除所有的进程组
removeAllProcessGroups();
//启动CPU监控线程
mProcessCpuThread.start();
//注册电池、权限管理相关服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
//将AMS的内部类LocalService对象放入到LocalServices内部的map集合中,
//其中ActivityManagerService.LocalService继承ActivityManagerInternal类
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManagerInternalAdded();
mUgmInternal.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other access to mProcessCpuTracker from main thread
// will be blocked during mProcessCpuTracker initialization.
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
接着看最上方 SystemServer的startBootstrapServices() 方法中的一句话:
mActivityManagerService.setSystemProcess();
/**
*这个方法 设置系统进程,AMS的setSystemProcess主要:
* 注册一些服务:activity、procstats、meminfo、gfxinfo、dbinfo、cpuinfo、permission、processinfo
关于服务的注册涉及binder相关内容,可以参考[Binder机制](https://www.likecs.com/default/index/url?u=aHR0cHM6Ly93d3cuY25ibG9ncy5jb20vZmFuZ2xvbmd4aWFuZy9wLzEzNDY2MjA0Lmh0bWw%3D)
* 在**起点**部分,attach()过程获取Context对象时通过ContextImpl.createAppContext()创建了一个LoadedApk(packagename是android,即framework-res.apk)。
这里获取包名为“android”的应用的ApplicationInfo对象,并将该ApplicationInfo信息安装设置到SystemThread(系统进程主线程)。即可以理解,系统也是一个特殊的应用。
* 创建ProcessRecord维护进程的相关信息,这里MY_PID即为SystemServer进程ID。
* 启动 检测应用运行和交互
*/
public void setSystemProcess() {
try {
//将AMS添加到ServiceManager中
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
//注册服务procstats,进程状态
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
//注册服务meminfo,内存信息
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
/ /注册服务gfxinfo,图像信息
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
//注册服务dbinfo,数据库信息
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
//注册服务cpuinfo,cpu信息
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
//注册服务permission和processinfo,权限和进程信息
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
//获取“android”应用的ApplicationInfo,并装载到mSystemThread
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
//创建ProcessRecord维护进程的相关信息
synchronized (this) {
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
false,
0,
new HostingRecord("system"));
app.setPersistent(true);
app.pid = MY_PID;
app.getWindowProcessController().setPid(MY_PID);
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
mPidsSelfLocked.put(app);
mProcessList.updateLruProcessLocked(app, false, null);
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
}
} 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);
}
}
}
});
}
到此AMS的启动基本结束。
上面提到的SystemServer的run方法,接着看下startOtherServices方法中AMS做了什么:
private void startOtherServices() {
......
//为SystemServer进程安装ContentProvider对象
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);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
traceEnd();
traceBeginAndSlog("SetWindowManagerService");
//设置WindowManager(WMS)
mActivityManagerService.setWindowManager(wm);
if (safeMode) {
//设置安全模式
mActivityManagerService.enterSafeMode();
}
if (safeMode) {
//设置安全模式的View
mActivityManagerService.showSafeModeOverlay();
}
//AMS启动完毕
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
traceBeginAndSlog("StartActivityManagerReadyPhase");
//标记SystemServer的阶段
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
traceEnd();
traceBeginAndSlog("StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
......
try {
//启动系统UI
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
});
......
}
看下ActivityManagerService的systemReady方法:
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
traceLog.traceBegin("PhaseActivityManagerReady");
synchronized(this) {
////第一次进入mSystemReady为false
if (mSystemReady) {
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}
//关键服务等待systemReady,继续完成一些初始化或进一步的工作
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
//调用各种服务的Ready方法
mActivityTaskManager.onSystemReady();
// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();
mAppOpsService.systemReady();
mSystemReady = true;
}
try {
//获取设备识别字符串
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}
//收集目前已经存在的进程(mPidsSelfLocked中保留了当前正在运行的所有进程信息)
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
//已启动的进程,若进程没有FLAG_PERSISTENT标志,则会被加入到procsToKill中
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
//销毁在AMS启动之前存在的进程(关闭procsToKill中的所有进程)
synchronized(this) {
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
mProcessList.removeProcessLocked(proc, true, false, "system update done");
}
}
// Now that we have cleaned up any update processes, we
// are ready to start launching real processes and know that
// we won't trample on them any more.
//到这里系统准备完毕
mProcessesReady = true;
}
Slog.i(TAG, "System now ready");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());
mAtmInternal.updateTopComponentForFactoryTest();
mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
watchDeviceProvisioning(mContext);
//初始化Settings变量
retrieveSettings();
mUgmInternal.onSystemReady();
final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
if (pmi != null) {
pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
state -> updateForceBackgroundCheck(state.batterySaverEnabled));
updateForceBackgroundCheck(
pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
} else {
Slog.wtf(TAG, "PowerManagerInternal not found.");
}
//运行goingCallback,SystemServer调用时传入的
if (goingCallback != null) goingCallback.run();
// Check the current user here as a user can be started inside goingCallback.run() from
// other system services.
final int currentUserId = mUserController.getCurrentUserId();
Slog.i(TAG, "Current user:" + currentUserId);
//获取UserId
if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
// User other than system user has started. Make sure that system user is already
// started before switching user.
throw new RuntimeException("System user not started while current user is:"
+ currentUserId);
}
traceLog.traceBegin("ActivityManagerStartApps");
//给BatteryStatsService发送状态
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
//SystemServiceManager设置UserId
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
// Only start up encryption-aware persistent apps; once user is
// unlocked we'll come back around and start unaware apps
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
// Start up initial activity.
mBooting = true;
......
//调用ActivityTaskManagerService的startHomeOnAllDisplays方法(就是启动launcher的Activity)
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
long ident = Binder.clearCallingIdentity();
try {
//发送一些广播ACTION_USER_STARTED 和 ACTION_USER_STARTING
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);
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);
......
}
}
主要关注几步:
1.关键服务等继续完成一些初始化或进一步工作
2.已启动的进程,若进程没有FLAG_PERSISTENT标志,则会被kill掉
3.运行goingCallback,即调用时传入的
4.启动launcher的Activity,即桌面应用
5.发送一些广播ACTION_USER_STARTED ACTION_USER_STARTING。
注:开机向导在这里可以在这里跳过,注意 watchDeviceProvisioning(mContext)和Settings.Secure.USER_SETUP_COMPLETE属性。
根据以上内容,在系统准备完成之后,mSystemReady=true,调用goingCallback 的run方法:
mActivityManagerService.systemReady(() -> {
//以下是goingCallback的run方法内容
Slog.i(TAG, "Making services ready");
traceBeginAndSlog("StartActivityManagerReadyPhase");
//启动阶段PHASE_ACTIVITY_MANAGER_READY=550
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
traceEnd();
traceBeginAndSlog("StartObservingNativeCrashes");
try {
//监测Native Crash
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
traceEnd();
// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
//启动WebView相关
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
traceEnd();
}
traceBeginAndSlog("StartSystemUI");
try {
//启动SystemUi
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
traceEnd();
......
// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();
// It is now okay to let the various system services start their
// third party code...
traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
// confirm webview completion before starting 3rd party
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
//启动阶段PHASE_THIRD_PARTY_APPS_CAN_START=1000
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
traceEnd();
......
}, BOOT_TIMINGS_TRACE_LOG);
看下上面提到的启动阶段定义:
/frameworks/base/services/core/java/com/android/server/SystemService.java
public abstract class SystemService {
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
public static final int PHASE_BOOT_COMPLETED = 1000;
}
当桌面启动完成后,发送开机广播ACTION_BOOT_COMPLETED。(这里不赘述,可以从Launcher的resume阶段开始,调用AMS.finishBooting()方法发送)
总结
大致总结下AMS的启动。
1.系统启动后Zygote进程第一个fork出SystemServer进程
2.SystemServer->run()->createSystemContext():创建了系统的ActivityThread对象,运行环境mSystemContext、systemUiContext。
3.SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():AMS在引导服务启动方法中,通过构造函数new ActivityManagerService()进行了一些对象创建和初始化(除activity外3大组件的管理和调度对象创建;内存、电池、权限、性能、cpu等的监控等相关对象创建),start()启动服务(移除进程组、启动cpu线程、注册权限、电池等服务)。
4.SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():AMS创建后进行了一系列相关的初始化和设置。
setSystemProcess():将framework-res.apk的信息加入到SystemServer进程的LoadedApk中,并创建了SystemServer进程的ProcessRecord,加入到mPidsSelfLocked,由AMS统一管理。
5.SystemServer->run()->startOtherServices():AMS启动后的后续工作,主要调用systemReady()和运行调用时传入的goingCallback。
systemReady()/goingCallback:各种服务或进程等AMS启动完成后需进一步完成的工作及系统相关初始化。 桌面应用在systemReady()方法中启动,systemui在goingCallback中完成。当桌面应用启动完成后,发送开机广播ACTION_BOOT_COMPLETED,到此为止。
网友评论