可以大概理解为所有与application有关的调用都会通过Instrumentation这样一个仪器来方便地观察到;换句话说就是,所有有关application的调用实际上都会通过Instrumentation;看一下其源码就可以看到它里面完成了许多功能:
public class Instrumentation {
private ActivityThread mThread = null;
private MessageQueue mMessageQueue = null;
private List mActivityMonitors;
public Application newApplication(ClassLoader cl, String className, Context context) {}
public Activity newActivity(ClassLoader cl, String className,
Intent intent) {}
public void callActivityOnNewIntent(Activity activity, Intent intent) {}
public ActivityResult execStartActivity(){}
}
二、Activity启动流程分析
例如App1要启动App2的一个Activity;Activity启动流程分析如下:
1. App1中的SampleActivity1启动App2的SampleActivity2
public class SampleActivity1 {
public void onClick() {
Intent intent = getPackageManager().getLaunchIntentForPackage(“com.app2.sample”);
startActivity(intent);
}
}
2. Activity源码分析
public class Activity {
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
public void startActivity(Intent intent, @Nullable Bundle options) {
// …
startActivityForResult(intent, -1);
}
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());
}
}
}
可以看到,Activity的startActivity最终都调用到了Instrumentation里面;
3. Instrumentation源码分析
继续分析Instrumentation的execStartActivity()方法:
public class Instrumentation {
/**
- 可以看到传递的参数中比较重要的几个:
-
- context who:就是前面的SampleActivity1
-
- IBinder contextThread:传的value是mMainThread.getApplicationThread(),即当前APP进程,这样AMS进程才可以通过IBinder与App1进程通信(比如将结果返回,就需要binder通信)
-
- IBinder token:又见IBinder,那一定也是别的进程需要通过这个IBinder进行通信
-
- Intent intent:启动参数
**/
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
// 省略部分代码…
try {
int result = ActivityTaskManager.getService()
.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) {
throw new RuntimeException(“Failure from system”, e);
}
return null;
}
}
- Intent intent:启动参数
可以看到,又继续调用到了ActivityTaskManager.getService().startActivity()里面。
ps. 在android-28源码中是调用到了ActivityManager.getService().startActivity()里面,更老版本android源码中是调用了ActivityManagerNative.getDefault(),原理都类似,都是调用返回一个代理,最终到了系统进程去执行后续调起逻辑。
4. ActivityTaskManager源码分析
@SystemService(Context.ACTI