activity 的启动流程
ActivityManagerService(ActivityManagerNative)
ActivityStackSupervisor 管理整个手机任务栈
ActivityStack Activity的栈(任务栈)
PackageManagerService(完成组件在清单里的扫描和注册)
ActivityThread(安卓java应用层的入口函数类)
C/S 架构思想
ServiceManager
多进程多任务多窗口多app
分模块思想
Activity
分层次思想
在Activity里面启动应用最终会走到startActivityForResult()
1、Activity#startActivityForResult()
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
mInstrumentation是Activity的成员变量,它用来监控应用程序和系统的交互;
mMainThread也是Activity的成员变量,都是通过attach()方法在ActivityThread创建Activity的时候传递给Activity作为成员变量。
mMainThread.getApplicationThread(),获取到的是ApplicationThread类型的对象,他是Activty的一个内部类,继承于ApplicationThreadNative,是一个binder对象ActivityThread远程交互存根,ActivityManagerService(继承于ActivityManagerNative)会使用它来和ActivityThread来进行进程间通信,Activity、Service的创建、生命周期都是它与系统ActivityManagerService来交互的
2、Instrumentation#execStartActivity()
int result = ActivityManagerNative.getDefault()//拿到ActivityManagerServiece的远程代理
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
- ActivityManagerNative.getDefault()拿到的是ActivityManagerService(通过ManagerService)系统服务在当先进程的本地代理(Proxy),startActivity()调用的是ActivityManagerProxy.startActivity方法。
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
data.writeString(callingPackage);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
if (options != null) {
data.writeInt(1);
options.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
可以看到这里就就是进行进程间通讯了
- whoThread:ApplicationThread,一个binder对象,作为参数将会传递到AcitivityMangerService远程服务中,后面会用此作为远程回调,在AtivityThread中对Activity的生命周期的控制都是在这个类里面。
- 另外传入的参数还有intent、应用包名等等。
开始跨进程
3、ActivityManagerService#startActivity()
通过上一步就调用到ActivityManagerService中来,属于系统服务进程,已经进行了跨进程操作。
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, options,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, false, userId, null, null);
}
ActivityStackSupervsior是用用来管理手机所有的Activity的栈信息的一个类
4、ActivityStackSupervsior.startActivityMayWait()
// Collect information about the target of the Intent.
ActivityInfo aInfo =
resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
resolveActivity{
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS, userId);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
aInfo = null;
}
if (aInfo != null) {
// Store the found target back into the intent, because now that
// we have it we never want to do this again. For example, if the
// user navigates back to this point in the history, we should
// always restart the exact same activity.
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
}
AppGlobals.getPackageManager()拿到PackageManagerService系统服务,去扫描所有的app(IPC),拿到符合intent匹配规则的Activity的相关信息保存到aInfo中。aInfo是一个ActivityInfo类型,他包含了在Manifest中注册Activity的所有信息和一些其他启动需要的信息。
5、ActivityStackSupervsior.startActivityLocked
验证intent、Class、Permission等
保存将要启动的Activity的Record
//把启动的应用的进程信息保存到callerApp中
callerApp = mService.getRecordForAppLocked(caller);
ProcessRecord callerApp 保存的是启动应用的进程信息,反正xxxRecord顾名思义就是用来记录信息用的。
ActivityRecord保存了Activity所需要的很多的信息
startActivityUncheckedLocked():
{
int launchFlags = intent.getFlags();
if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0
&& r.resultTo.task.stack != null) {
// For whatever reason this activity is being launched into a new
// task... yet the caller has requested a result back. Well, that
// is pretty messed up, so instead immediately send back a cancel
// and let the new task continue launched as normal without a
// dependency on its originator.
Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
r.resultTo.task.stack.sendActivityResultLocked(-1,
r.resultTo, r.resultWho, r.requestCode,
Activity.RESULT_CANCELED, null);
r.resultTo = null;
}
}
检查将要启动的Activity的launchMode和启动Flag,根据launcheMode和Flag配置task
6、ActivityStack.startActivityLocked()
去检查是否要简历新的任务栈
7、ActivityStackSupervsior.resumeTopActivityLocked()
查找需要暂停的Activity。
8、ActivityStack---------->startPausingLocked()
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
这里调用到ActivityThread的ApplicationThread的远对象,进行进程间通讯
正式让之前的Activity暂停
告诉AMS已经暂停完成
9.ApplicationThread.handlePauseActivity()
在用户进程执行performPauseActivity(token, finished, r.isPreHoneycomb());最终调用Activity的onPause(),等到Activity暂停之后再次和AMS进程通信调用:ActivityManagerNative.getDefault().activityPaused(token);告诉AMS Activity已经暂停,可以启动新的Activity。
10、AMS-->activityPaused()
11.ActivityStack->activityPausedLocked()->finishCurrentActivityLocked()
12.ActivityStackSuperVisor------> resumeTopActivitiesLocked()
13.ActivityStack----------------> resumeTopActivityLocked()
该进程不存在,创建进程
14.ActivityStackSuperVisor------> startSpecificActivityLocked()
15.ActivityManagerService-------> startProcessLocked()
16.Process.start()
这里主要是调用Process.start接口来创建一个新的进程,新的进程会导入android.app.ActivityThread类,并且执行它的main函数,这就是为什么我们前面说每一个应用程序都有一个ActivityThread实例来对应的原因
17.ActivityThread.main()
18.AMS.attachApplication();
函数attach最终调用了ActivityManagerService的远程接口ActivityManagerProxy的attachApplication函数,传入的参数是mAppThread,这是一个ApplicationThread类型的Binder对象,它的作用是用来进行进程间通信的
19 ActivityManagerProxy.attachApplication
20.ActivityManagerService.attachApplicationLocked
准备启动应用,先查找MainActivity
21ActivityStackSuperVisor------>attachApplicationLocked--->realStartActivityLocked()
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
21 ActivityThread----------> scheduleLaunchActivity()
最终通过IPC调用到ActivityThread的scheduleLaunchActivity()来执行Activity的生命周期的函数。