AMS如何拿到App的Binder
Zygote接受到socket信息后,fork出App进程。首先关掉App进程的Socket,然后初始化运行时的Runtime,初始化Binder物理驱动和Binder线程池。最后反射找到ActivityThread的main方法执行。在main方法里面除了为主线程创建一个looper,并且开启死循环以外。还执行了ActivityThread的attach方法。
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
......
//获取AMS的本地代理类
final IActivityManager mgr = ActivityManager.getService();
try {
//通过Binder调用AMS的attachApplication方法
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
......
}
在attach方法里面通过ServiceManager.getService(Context.ACTIVITY_SERVICE)先拿到AMS的Binder,然后再通过IActivityManager.Stub.asInterface拿到AMS的本地代理类。
/**
* @hide
*/
@UnsupportedAppUsage
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
@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的Binder调用AMS的attachApplication方法,完成App端对System_service请求的跨进程通信,这这次跨进程通信中,把App的Binder传给了AMS。
@GuardedBy("this")
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
// Find the application record that is being attached... either via
// the pid if we are running in multiple processes, or just pull the
// next app record if we are emulating process with anonymous threads.
ProcessRecord app;
......
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid);
......
//执行ActivityThread里面ApplicationThread的bindApplication函数
//这里通过App的Binder和App通信
thread.bindApplication(processName, appInfo, providerList,
instr2.mClass,
profilerInfo, instr2.mArguments,
instr2.mWatcher,
instr2.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
app.mDisabledCompatChanges);
//把我们的APP的Binder存到对应的ProcessRecord里面
app.makeActive(thread, mProcessStats);
//把我们的App对应的ProcessRecord存放到ProcessList里面方便统一管理
mProcessList.updateLruProcessLocked(app, false, null);
......
//mAtmInternal就是ActivityTaskManagerInternal.class,里面有大部分AMS的服务
//调用 mAtmInternal 的attachApplication(),最终层层调用到ActivityStackSupervisor.java的 realStartActivityLocked()
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
......
AMS的attachApplication最终会调用到AMS的attachApplicationLocked方法里面,在这个方法里面先通过ProcessList拿到进程对应的ProcessRecord,并且把进程的Binder存储到ProcessRecord里面。
Application生命周期怎么启动的
在存储App的Binder到进程对应的ProcessRecord之前,会执行ActivityThread里面ApplicationThread的bindApplication函数,ApplicationThread就是Binder线程池里面的一个子线程,需要通过sendMessage把相关信息发送到主线程里面去创建Application。
//Binder线程池里面的一个线程
private class ApplicationThread extends IApplicationThread.Stub {
......
@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) {
......
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把消息发送到主线程,然后主线程接受到消息,执行handleBindApplication方法
@UnsupportedAppUsage
private void handleBindApplication(AppBindData data) {
......
Application app;
final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
try {
// If the app is being launched for full backup or restore, bring it up in
// a restricted environment with the base application class.
//创建一个Application,通过反射来创建
//并且会执行Appliaction的attach方法,在这个方法里面执行attachBaseContext
app = data.info.makeApplication(data.restrictedBackupMode, null);
.....
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
//创建contentProvide,执行相应的生命周期
installContentProviders(app, data.providers);
}
}
......
try {
//执行Application的onCreate方法
mInstrumentation.callApplicationOnCreate(app);
}
......
可以看到在主线程的handleBindApplication方法里面,通过makeApplication函数,在内部通过反射来创建Application。
并且会执行Appliaction的attach方法,在这个方法里面执行attachBaseContext
@UnsupportedAppUsage
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
// 如果已经创建过 Application,则直接返回,保证Application是单例的
if (mApplication != null) {
return mApplication;
}
......
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
final 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);
}
......
//传入 ClassLoader、全类名等参数,通过返回创建 Application 对象
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
}
......
return app;
}
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
// 通过反射创建 Application 对象
Application app = getFactory(context.getPackageName())
.instantiateApplication(cl, className);
app.attach(context);
return app;
}
@UnsupportedAppUsage
/* package */ final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
接着会创建contentProvide,执行相应的生命周期,最后才是执行创建的Appliaction的onCreate方法。