ActivityManagerService属于系统核心服务,主要负责管理Activity等组件,是由SystemServer启动的
//frameworks/base/services/java/com/android/server/SystemServer.java
private void run(){
//做一些初始化操作,主要创建systemserver的Context以及ActivityThread
createSystemContext();
startCoreServices(t);
startOtherServices(t);
//ams在这里面
startBootstrapServices(t);
Looper.loop();
}
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
//startService先通过反射创建了ActivityTaskManagerService.Lifecycle对象(在其构造函数里面创建了ActivityTaskManagerService),
// 并调用了Lifecycle的onStart():在这里atm被注册到了ServiceManager中,publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService)
// 接着调用getService拿到atm
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//内部同样是通过mSystemServiceManager.startService()启动,也就是依旧反射创建了ActivityManagerService.Lifecycle,
//调用了Lifecycle的onStart():调用了ams的start:mService.start();
// 返回Lifecycle构造函数创建了ActivityManagerService
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//ams真正向ServiceManager注册Binder:
mActivityManagerService.setSystemProcess();
}
//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void setSystemProcess() {
//注册各种service
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);//这个是activity
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));
ServiceManager.addService("cacheinfo", new CacheBinder(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
//加载framework-res.apk
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
}
可以看出,在systemserver中主要是像servicemanager注册了各种service,然后陷入looper中等待通讯。
而AMS相关主要是ActivityManagerService以及ActivityTaskManagerService
从ActivityTaskManagerService的类注释来看,它才是真正负责管理活动和容器的类,而ams主要是持有它,做一个代理工作?
//至此AMS服务已经启动起来了,接下来我们从startActivity入手,在实际中看一下,历经了哪些类,分别都处理了什么
//frameworks/base/core/java/android/app/Activity.java
//startActivity最终调用均为startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
}
//可以看到出现了多个全局变量
// mInstrumentation:Instrumentation,
// mMainThread:ActivityThread,
// mMainThread.getApplicationThread:ApplicationThread
// 这些变量都是在attach函数赋值的,具体attach是什么时候回调的,我们暂时放下到后续的分析中查看
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
attachBaseContext(context);
//...
mMainThread = aThread;
mInstrumentation = instr;
//...
}
//我们继续查看execStartActivity
//frameworks/base/core/java/android/app/Instrumentation.java:Instrumentation是Android系统提供的用来hook控制组件生命周期的类
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//可以看到最终走到了ActivityTaskManagerService:从启动应用进程进入了SystemServer进程
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
}
//********************SystemServer进程***************************
//frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
//startActivityAsUser 是几个重载函数,最终走到:
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");
//通过ActivityStartController创建了ActivityStarter并进行一系列链式调用进行了配置(内部会把各个值设置给Request(mRequest)保存),然后调用其execute
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();
}
//frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
//frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
//ActivityStarter用于解释Activity是在什么时候、怎样启动的一个控制器。这个类用于确定intent 和 flags 应如何转换为 activity 以及相关任务和堆栈的所有逻辑
int execute() {
try {
int res;
res = executeRequest(mRequest);
return getExternalResult(mRequest.waitResult == null ? res: waitForResult(res, mLastStartActivityRecord));
} finally {
//一些收尾工作,把当前的ActivityStarter设置为lastStarter
onExecutionComplete();
}
}
//这里主要是做一些启动前的检查,然后通过startActivityUnchecked->startActivityInner继续进行后续启动
private int executeRequest(Request request) {
mLastStartReason = request.reason;
mLastStartActivityRecord = null;
final IApplicationThread caller = request.caller;
Intent intent = request.intent;
NeededUriGrants intentGrants = request.intentGrants;
String resolvedType = request.resolvedType;
ActivityInfo aInfo = request.activityInfo;
ResolveInfo rInfo = request.resolveInfo;
final IVoiceInteractionSession voiceSession = request.voiceSession;
final IBinder resultTo = request.resultTo;
String resultWho = request.resultWho;
int requestCode = request.requestCode;
int callingPid = request.callingPid;
int callingUid = request.callingUid;
String callingPackage = request.callingPackage;
String callingFeatureId = request.callingFeatureId;
final int realCallingPid = request.realCallingPid;
final int realCallingUid = request.realCallingUid;
final int startFlags = request.startFlags;
final SafeActivityOptions options = request.activityOptions;
Task inTask = request.inTask;
int err = ActivityManager.START_SUCCESS;
final Bundle verificationBundle =
options != null ? options.popAppVerificationBundle() : null;
WindowProcessController callerApp = null;
if (caller != null) {
//mService : ActivityTaskManagerService:
//caller : IApplicationThread
//这里是拿到启动Activity的WindowProcessController:应该是每个启动的进程都会走到ATM里,add缓存上自己的?
callerApp = mService.getProcessController(caller);
if (callerApp != null) {
callingPid = callerApp.getPid();
callingUid = callerApp.mInfo.uid;
}
}
final int userId = aInfo != null && aInfo.applicationInfo != null
? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
if (sourceRecord != null) {
//如果是startActivityForResult,并且启动activity没有finish掉,那么被启动的activity的返回activity还是之前的启动activity
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
//ActivityRecord即是Activity的数据结构类,一个ActivityRecord对应一个Activity,此处构造待启动的activity
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
mLastStartActivityRecord = r;
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,request.voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask,restrictedBgActivity, intentGrants);
return mLastStartActivityResult;
}
//启动前校验完毕后走到startActivityUnchecked,主要是负责继续启动,以及启动如果失败后的remove工作
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.deferWindowLayout();
//继续进行启动
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {
//启动成功后,拿到新activity的栈信息
startedActivityStack = handleStartResult(r, result);
mService.continueWindowLayout();
}
postStartActivityProcessing(r, result, startedActivityStack);
return result;
}
网友评论