每个Activity都持有Instrumentation对象的一个引用,但是整个进程只会存在一个Instrumentation对象 。当startActivityForResult()调用之后,实际上还是调用了mInstrumentation.execStartActivity()
startActivityForResult()------> minstrumentation.execStartActivity()方法。
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
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());
}
...ignore some code...
} else {
if (options != null) {
//当现在的Activity有父Activity的时候会调用,但是在startActivityFromChild()内部实际还是调用的mInstrumentation.execStartActivity()
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
...ignore some code...
}
mInstrumentation.execStartActivity(): ?
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...ignore some code...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}
在程序中调用startActivity()的 时候,实际上调用的是Instrumentation的相关的方法。
Instrumentation:“仪器”,这个类里面包含哪些方法:
Instrumentation类里面的方法大多数和Application和Activity有关,这个类就是完成对Application和Activity初始化和生命周期的工具类。比如,callActivityOnCreate()
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
activity.performCreate(icicle); 就是默认相应 onCreate 方法,将icicle Bundle数据传递过去 ?
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
Instrumentation这个类很重要,对Activity生命周期方法的调用根本就离不开他,他可以说是一个大管家,仅内部调用 外部就是?ActivityThread :UI线程 ?
App进程和AMS是通过Binder传递信息的,那么ActivityThread(UI线程)就是专门与AMS交互
比如:AMS说:“ActivityThread,你给我暂停一个Activity!” ActivityThread就说:“没问题!”然后转身和Instrumentation说:“老婆,AMS让暂停一个Activity,我这里忙着呢,你快去帮我把这事办了把~” 于是,Instrumentation就去把事儿搞定了
AMS是大BOSS资本,负责指挥和调度的,ActivityThread是企业老板,虽然说企业的事自己说了算,但是需要听从AMS的指挥,而Instrumentation则是CTO,负责项目的大事小事,但是一般不抛头露面,听老板ActivityThread的安排。
?
|