1、Activity
public class Activity extends ContextThemeWrapper implements LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2, Window.OnWindowDismissedCallback, WindowControllerCallback {
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
//与AMS通信,实例化Activity并拿到结果
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
if (ar != null) {//拿到结果后,通过ActivityThread把消息传给主线程
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
}
if (requestCode >= 0) {//大于0说明是startActivityForResult()要结果的
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
/* startActivityFromChild()做的事,跟mParent==null时差不多
* 1)mInstrumentation.execStartActivity(...)
* 2)mMainThread.sendActivityResult(...)
*/
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
}
2、Instrumentation.java
public class Instrumentation {
public ActivityResult execStartActivity(...) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
/* 这里是关键
* ActivityManagerNative.getDefault()拿到ActivityManagerProxy,调用startActivity()与AMS通信,调用到AMS的startActivity(...)
* AMS.startActivity()之后的事情,看上一篇博客就知道了
*/
int result = ActivityManagerNative.getDefault().startActivity(....);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
启动Activity到了AMS中,会根据传入的processName等信息从mPidsSelfLocked(它是个SparseArray) 取出pid(进程id),如果不存在,则调用startProcessLocked(app, "link fail", processName);创建新的进程,startProcessLocked(...)内部是向Zygote进程发送一个socket请求,fork一个新的进程。Zygote进程之前有写过,里面有注册socket接口,用来和ActivityManagerService通讯,当收到AMS发送的socket请求时,fork新的进程。
从源码看AndroidManagerService(一)AMS的启动
从源码看AndroidManagerService(二)简单了解ActivityManager与AMS的通信