我们启动一个Activity时,一般使用
Intent intent = new Intent(mainActivity.this,otherActivity.class);
context.startActivity(intent);
public abstract void startActivity(Intent intent,Bundle options);
public abstract void startActivity(Intent intent);
我们常用的Context
有Application
、Activity
和Service
,其中Application
和Service
直接继承ContextWrapper
,而Activity
涉及到View
所以通过继承ContextThemeWrapper
间接的继承了ContextWrapper
,ContextWrapper
包装的Context
的实现类是ContextImpl
。因此我们基本都是调用ContextImple
的实现方法去执行startActivity
的!
frameworks/base/core/java/android/app/Activity.java
public class Activity extends ContextThemeWrapper{
...
public void startActivity(Intent intent,Bindle options){
if(options!=null){
startActivityForResult(intent,-1,options);
} else startActivityForResult(intent,-1);
}
}
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
ApplicationThread at = mMainThread.getApplicationThread();
//
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, at, mToken, this, intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode,
ar.getResultCode(), ar.getResultData());
}
if (requestCode >= 0) {
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
Instrumentation#execStartActivity()
public ActivityResult execStartActivity( Context who, IBinder contextThread,
IBinder token, Activity target, Intent intent,
int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManager.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;
}
最终调用ActivityManager.getService().startActivity()
可以看到这里最终调用了ActivityManager.getService().startActivity()
,类似AMS 的启动过程,这里是获取了IActivityManager
实例,IActivityManager
基于 AIDL 实现 Binder,了解 Binder 的话就会知道,因为 App 进程和 AMS 的进程system_server
不是同一个进程,所以这里获取到的是 AMS 的IActivityManger
在服务端代理,不过这里还会远程调用到 AMS 中去
frameworks/base/core/java/android/app/ActivityManager.java
public static IActivityManager getService(){
return IActivityManagerSingleton.get();
}