一. 基本知识
ServiceManger是一个后台守护进程,由init进程读取init.rc文件启动,会一直保存在后台。
SystemServer由Zygote进程启动,主要负责启动服务,如AMS,WMS等,并且把这些服务的binder存到ServiceManager里面。
SystemServiceManger是SystemServer进程里面帮助SystemServer管理各种服务的管理类,他专门管理和启动一系列服务。如下图:
AMS,WMS都不是独立的进程,只是SystemServer进程里面的变量而已。
二.总体流程
在Launcher进程里面,点击app图标时候,会调用ServiceManager.getService方法获取AMS的binder,通过binder与保存在SystemService里面的AMS通信,AMS通过socket发送消息给zygote进程,通知zygote去fork出app进程。在zygote创建app进程的时候,会反射执行ActivityThread的main方法,随后和AMS跨进程通信
二.SystemServer里面保存大量服务(AMS,WMS等),与app如何通信呢?
思考:为什么静态方法在哪都可以调用呢?给一个方法加上static,实际上做了什么?
SystemServer进程和app进程是两个不同的进程,不能直接通信,需要跨进程通信。ServiceManger是独立的进程,里面封装了一个静态的getService方法,对外暴露Binder,谁都可以调用这个方法去拿对应的Binder(静态方法谁都可以调用)。getService代码如下:
/**
* Cache for the "well known" services, such as WM and AM.
*/
@UnsupportedAppUsage
private static Map<String, IBinder> sCache = new ArrayMap<String, IBinder>();
/**
* Returns a reference to a service with the given name.
*
* @param name the name of the service to get
* @return a reference to the service, or <code>null</code> if the service doesn't exist
*/
@UnsupportedAppUsage
public static IBinder getService(String name) {
try {
IBinder service = sCache.get(name);
if (service != null) {
return service;
} else {
return Binder.allowBlocking(rawGetService(name));
}
} catch (RemoteException e) {
Log.e(TAG, "error in getService", e);
}
return null;
}
让我们来看一下具体的调用,在Instrumentation类里面的execStartActivity方法里面:
/**
* Like {@link #execStartActivity(Context, IBinder, IBinder, Activity, Intent, int, Bundle)},
* but for starting as a particular user.
*
* @param who The Context from which the activity is being started.
* @param contextThread The main thread of the Context from which the activity
* is being started.
* @param token Internal token identifying to the system who is starting
* the activity; may be null.
* @param target Which fragment is performing the start (and thus receiving
* any result).
* @param intent The actual Intent to start.
* @param requestCode Identifier for this request's result; less than zero
* if the caller is not expecting a result.
*
* @return To force the return of a particular result, return an
* ActivityResult object containing the desired data; otherwise
* return null. The default implementation always returns null.
*
* @throws android.content.ActivityNotFoundException
*
* @see Activity#startActivity(Intent)
* @see Activity#startActivityForResult(Intent, int)
*
* {@hide}
*/
@UnsupportedAppUsage
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, String resultWho,
Intent intent, int requestCode, Bundle options, UserHandle user) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
ActivityResult result = null;
if (am.ignoreMatchingSpecificIntents()) {
result = am.onStartActivity(intent);
}
if (result != null) {
am.mHits++;
return result;
} else if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
int result = ActivityTaskManager.getService().startActivityAsUser(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token, resultWho,
requestCode, 0, null, options, user.getIdentifier());
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
ActivityTaskManager.getService()里面调用的是:
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
//获取服务:ACTIVITY_TASK_SERVICE = "activity_task",对应的服务为ATM-ActivityTaskManagerService
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);//ServiceManagerProxy
return IActivityTaskManager.Stub.asInterface(b);
}
};
可以看到这边的ATMS是通过ServiceManager.getService获取的。
AMS,WMS是怎么保存在ServiceManager里面的呢?
我们知道SystemService里面启动服务的三个核心方法是:
// Start services.
try {
t.traceBegin("StartServices");
//AMS在这里面启动
startBootstrapServices(t);
startCoreServices(t);
//WSM在这里面启动
startOtherServices(t);
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
AMS启动方法是startBootstrapServices:
/**
* Starts the small tangle of critical services that are needed to get the system off the
* ground. These services have complex mutual dependencies which is why we initialize them all
* in one place here. Unless your service is also entwined in these dependencies, it should be
* initialized in one of the other functions.
*/
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
.......
// Activity manager runs the show.
t.traceBegin("StartActivityManager");
// TODO: Might need to move after migration to WM.
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService(); //启动atms
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm); // 启动AMS
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();
......
// 核心内容,为app进程安排系统进程的以便后期监控
// Set up the Application instance for the system process and get started.
t.traceBegin("SetSystemProcess");
//把AMS添加到ServiceManager里面
mActivityManagerService.setSystemProcess();
t.traceEnd();
......
}
创建AMS后,真正把AMS添加到ServiceManager里面的是AMS的setSystemProcess()方法:
//注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关
//的服务注册到ServiceManager。查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程
//序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的
//installSystemApplicationInfo方法。
//创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个
//ProcessRecord类型的对象,并保存该对象的信息
public void setSystemProcess() {
try {
// 注册服务activity
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));
// 注册缓存信息
ServiceManager.addService("cacheinfo", new CacheBinder(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
// 创建ProcessRecord维护进程的相关信息
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);
addPidLocked(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 (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
final int[] cameraOp = {AppOpsManager.OP_CAMERA};
mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
@Override
public void opActiveChanged(int op, int uid, String packageName, boolean active) {
cameraActiveChanged(uid, active);
}
});
}
里面的第一行代码就调用ServiceManager的addService方法把AMS的binder添加到ServiceManager里面。
WMS的启动方法是startOtherServices:
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
*/
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
......
// WMS needs sensor service ready
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
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);
t.traceEnd();
......
}
可以看到WMS在启动后立刻调用ServiceManager的addService方法把WMS的binder添加到ServiceManager里面。
总结:在Launcher进程里面,点击app图标时候,会调用ServiceManager.getService方法获取AMS的binder,通过binder与保存在SystemService里面的AMS通信,AMS通过socket发送消息给zygote进程,通知zygote去fork出app进程。
三.如何启动APP
我们已经知道点击app图标的时候,Launcher进程会到ServiceManager里面拿到AMS的binder,通过binder调用保存在SystemService里面的AMS,通知AMS发送socket消息给zygote进程fork出app进程。
我们知道zygote是init进程读取init.rc文件创建的名称叫app_main.cpp的进程,在app_main.cpp的main方法里面执行runtime.start("com.android.internal.os.ZygoteInit", args, zygote),通过反射创建ZygoteInit进程,ZygoteInit的main方法里面会分四步执行,第一步执行preload加载资源,第二步new ZygoteServer创建一个socket服务,第三步forkSystemServer方法fork出SystemServer进程,第四步循环等待fork出其他的应用进程。
由于ZygoteInit创建出SystemServer进程后就一直在循环等待AMS的消息,AMS通过socket发送消息给zygote进程后,在ZygoteServer里面的死循环就会接受到消息执行fork操作。
在ZygoteServer里面的死循环的代码如下:
/**
* Runs the zygote process's select loop. Accepts new connections as
* they happen, and reads commands from connections one spawn-request's
* worth at a time.
*/
Runnable runSelectLoop(String abiList) {
......
while (true) {
///重要细节///
// 进行进程的处理:创建进程
final Runnable command = connection.processOneCommand(this);
......
}
}
真正创建子进程的函数是processOneCommand:
/**
* Reads one start command from the command socket. If successful, a child is forked and a
* {@code Runnable} that calls the childs main method (or equivalent) is returned in the child
* process. {@code null} is always returned in the parent process (the zygote).
*
* If the client closes the socket, an {@code EOF} condition is set, which callers can test
* for by calling {@code ZygoteConnection.isClosedByPeer}.
*/
Runnable processOneCommand(ZygoteServer zygoteServer) {
String[] args;
try {
// 获取socket 命令参数
args = Zygote.readArgumentList(mSocketReader);
} catch (IOException ex) {
throw new IllegalStateException("IOException on command socket", ex);
}
......
// Fork子进程,得到一个新的pid
pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mIsTopApp,
parsedArgs.mPkgDataInfoList, parsedArgs.mWhitelistedDataInfoList,
parsedArgs.mBindMountAppDataDirs, parsedArgs.mBindMountAppStorageDirs);
try {
if (pid == 0) {
// in child
zygoteServer.setForkChild();
zygoteServer.closeServerSocket();
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
//处理子进程
return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);
} else {
// In the parent. A pid < 0 indicates a failure and will be handled in
// handleParentProc.
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
handleParentProc(pid, serverPipeFd);
return null;
}
} finally {
IoUtils.closeQuietly(childPipeFd);
IoUtils.closeQuietly(serverPipeFd);
}
}
小结:ZygoteInit创建出SystemServer进程后就一直在循环等待AMS的消息,AMS通过socket发送消息给zygote进程后,在ZygoteServer里面的死循环就会接受到消息执行processOneCommand函数,先拿到AMS通过socket发送过来的消息argv,然后调用Zygote.forkAndSpecialize函数fork出一个子进程得到这个进程的pid,此时app进程已经被启动了。
四.app被启动后如何启动acticity呢?
继续分析可知,processOneCommand创建完子进程后,会执行handleChildProc函数对子进程做处理:
private Runnable handleChildProc(ZygoteArguments parsedArgs,
......
if (!isZygote) {
// App 进程的启动
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, null /* classLoader */);
} else {
return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, null /* classLoader */);
}
......
}
在handleChildProc方法里面又回到ZygoteInit里面调用zygoteInit方法:
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();//初始化运行环境
ZygoteInit.nativeZygoteInit();//启动Binder ,方法在 androidRuntime.cpp中注册
// 通过反射创建程序入口函数的 Method 对象,并返回 Runnable 对象
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}
思考:RuntimeInit.commonInit()到底做了啥?
zygote方法里面一开始执行RuntimeInit.commonInit初始化运行环境,然后执行nativeZygoteInit方法启动Binder(每一个进程都存在对应的Binder),最后执行RuntimeInit.applicationInit方法,RuntimeInit.applicationInit里面的argv是AMS发送过来的,processOneCommand函数一开始就拿到了argv,最后会反射创建ActivityThread的main函数。
RuntimeInit.applicationInit:
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
// Android runtime shutdown hooks close the Binder driver, which can cause
// leftover running threads to crash before the process actually exits.
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
final Arguments args = new Arguments(argv);
// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// Remaining arguments are passed to the start class's static main
// startClass: 如果AMS通过socket传递过来的是 ActivityThread
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
// 通过反射拿到对应类的main方法的Method对象
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
return new MethodAndArgsCaller(m, argv);
}
这样就可以看出最后是反射创建了app的main函数,也就是ActivityThread的main函数:
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
// 安装选择性的系统调用拦截
AndroidOs.install();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
//之前SystemServer调用attach传入的是true,这里到应用进程传入false就行
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//一直循环,保障进程一直执行,如果退出,说明程序关闭
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
其中最重要的attach方法:
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取AMS的本地代理类
final IActivityManager mgr = ActivityManager.getService();
try {
//通过Binder调用AMS的attachApplication方法
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
// 为 ViewRootImpl 设置配置更新回调,
//当系统资源配置(如:系统字体)发生变化时,通知系统配置发生变化
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
// TODO (b/135719017): Temporary log for debugging IME service.
if (Build.IS_DEBUGGABLE && mHasImeComponent) {
Log.d(TAG, "ViewRootImpl.ConfigChangedCallback for IME, "
+ "config=" + globalConfig);
}
// We need to apply this change to the resources immediately, because upon returning
// the view hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
null /* compat */,
mInitialApplication.getResources().getDisplayAdjustments())) {
updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
mResourcesManager.getConfiguration().getLocales());
// This actually changed the resources! Tell everyone about it.
if (mPendingConfiguration == null
|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
mPendingConfiguration = globalConfig;
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
}
}
}
};
ViewRootImpl.addConfigCallback(configChangedCallback);
}
mAppThread是ActivityThread的binder,其中的 final IActivityManager mgr = ActivityManager.getService()最后会跑到ActivityManager类里面执行getService方法,可以看到最后实际上是访问了ServiceManager拿到了AMS的binder代理,通过binder访问AMS的attachApplication方法,并且把ActivityThread的binder传递给了AMS:
@UnsupportedAppUsage
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static IActivityTaskManager getTaskService() {
return ActivityTaskManager.getService();
}
@UnsupportedAppUsage
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
AMS的attachApplication:其中的thread是ActivityThread的
注意:AMS里面的mProcessList变量里面的arraylist保存了当前正在运行的app进程
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
//activity的binder 提供给ams
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
这里面的thread正是ActivityThread的binder,此时AMS已经拿到了ActivityThread的binder,AMS可以与ActivityThread进行通信了。对应整体流程里面的:
小结:app进程被启动后,在zygoteservice的processOneCommand创建完子进程后,会执行handleChildProc函数对子进程做处理,在handleChildProc方法里面又回到ZygoteInit里面调用zygoteInit方法,zygoteInit方法里面一开始执行RuntimeInit.commonInit初始化运行环境,然后执行nativeZygoteInit方法启动Binder(每一个进程都存在对应的Binder),最后执行RuntimeInit.applicationInit方法,RuntimeInit.applicationInit里面的argv是AMS发送过来的,processOneCommand函数一开始就拿到了argv,最后会反射创建ActivityThread的main函数。在ActivityThread的main函数里面调用attach方法,通过获取AMS的binder代理调用AMS的attachApplication方法,并且把ActivityThread的binder(mAppThread)传递给AMS,使得AMS能够与ActivityThread跨进程通信。
五.activity生命周期管理
在第四点中提到ActivityThread的binder(mAppThread)传递给AMS里面的mAppThread到底是什么?
我们可以看到在ActivityThread里面有一个内部类ApplicationThread,这个就是mAppThread:
private class ApplicationThread extends IApplicationThread.Stub
可以看到这个ApplicationThread其实是一个Binder代理。我们把ApplicationThread传给AMS了,AMS和ActivityThread通信其实就是和ApplicationThread通信,其实就是调用ApplicationThread里面的函数。
Application对象的创建在ApplicationThread的bindApplication函数:
@Override
public final void bindApplication(String processName, ApplicationInfo appInfo,
ProviderInfoList providerList, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
if (services != null) {
if (false) {
// Test code to make sure the app could see the passed-in services.
for (Object oname : services.keySet()) {
if (services.get(oname) == null) {
continue; // AM just passed in a null service.
}
String name = (String) oname;
// See b/79378449 about the following exemption.
switch (name) {
case "package":
case Context.WINDOW_SERVICE:
continue;
}
if (ServiceManager.getService(name) == null) {
Log.wtf(TAG, "Service " + name + " should be accessible by this app");
}
}
}
// Setup the service cache in the ServiceManager
ServiceManager.initServiceCache(services);
}
setCoreSettings(coreSettings);
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providerList.getList();
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillOptions = autofillOptions;
data.contentCaptureOptions = contentCaptureOptions;
data.disabledCompatChanges = disabledCompatChanges;
sendMessage(H.BIND_APPLICATION, data);
}
可以看到这个方法最后调用了sendMessage(H.BIND_APPLICATION, data),最后会跑到handleMessage方法里面执行handleBindApplication方法:
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
.....
}
}
}
handleBindApplication方法里面又通过调用data.info.makeApplication(data.restrictedBackupMode, null)来反射创建Application 对象。
小结:我们知道AMS里面会管理android四大组件的生命周期,其实就是ApplicationThread在管理生命周期。AMS拿到ActivityThread的Binder后,传送消息给mAppThread,在mAppThread完成跨进程通信后,然后转换为当前进程的message。bindApplication方法拿到AMS发送的消息,然后通过sendMessage(H.BIND_APPLICATION, data)跑到handleMessage方法里面执行handleBindApplication(data),最后通过
app = data.info.makeApplication(data.restrictedBackupMode, null)方法反射创建出application。
问题1.activity在哪个方法创建的
问题2.zygoteInit进程的zygoteInit方法里面的RuntimeInit.commonInit()有啥作用