当前位置:   article > 正文

Activity启动流程(一)_startactivity参数

startactivity参数

  • Launcher进程请求AMS
  • AMS发送创建应用进程请求
  • Zygote进程接受请求并孵化应用进程
  • 应用进程启动ActivityThread

    一、Launcher进程请求AMS

    上面我们提到根Activity的启动流程其实就是桌面上点击一个应用图标进入到应用的第一个Activity的流程,其实桌面也可以看成一个程序,即Launcher。当系统开机后,Launcher也随之被启动,然后将已经安装的应用程序图标显示到桌面上,所以当我们点击一个应用图标其实就是相当于点击活动中的一个button,其相应事件就是Launcher进程请求AMS来启动该应用程序。

    1. 时序图

    在这里插入图片描述

    2. 详细过程

    请求的入口就是Launcher的startActivitySafe方法,如下:

    packages/apps/Launcher3/src/com/android/launcher3/Launcher.java

    1. public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
    2. ...
    3. // 根Activity会在新的任务栈中启动
    4. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    5. try {
    6. ...
    7. if (isShortcut) {
    8. // Shortcuts need some special checks due to legacy reasons.
    9. startShortcutIntentSafely(intent, optsBundle, item);
    10. } else if (user == null || user.equals(Process.myUserHandle())) {
    11. // 调用startActivity
    12. startActivity(intent, optsBundle);
    13. } else {
    14. LauncherAppsCompat.getInstance(this).startActivityForProfile(
    15. intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
    16. }
    17. ...
    18. return true;
    19. } catch (ActivityNotFoundException|SecurityException e) {
    20. ...
    21. }
    22. return false;
    23. }
    24. 复制代码

    可以发现该方法为根Activity设置了flag,即根Activity会在新的任务栈中启动。然后会调用我们熟悉的startActivity方法,而在Launcher并没有这个方法,所以我们自然想到了应该是父类的方法,然后让我们来看看Launcher继承了哪些类?

    1. public class Launcher extends BaseDraggingActivity implements LauncherExterns,
    2. LauncherModel.Callbacks, LauncherProviderChangeListener, UserEventDelegate{
    3. }
    4. public abstract class BaseDraggingActivity extends BaseActivity
    5. implements WallpaperColorInfo.OnChangeListener {
    6. }
    7. public abstract class BaseActivity extends Activity implements UserEventDelegate{
    8. }
    9. 复制代码

    其实一直追踪下去,你就会发现其实Launcher调用的startActivity其实就是Activity中的startActivity。从这里也可以证明Launcher其实也是个Activity。所以在Launcher启动一个app,和我们平时在startActivity基本是一样的(基本一样,不代表完全一样,通过后文分析你就会明白!),于是我们来看看我们熟悉的Activity中的startActivity的源码是如何的:

    源码:frameworks/base/core/java/android/app/Activity.java

    1. @Override
    2. public void startActivity(Intent intent, @Nullable Bundle options) {
    3. //第二个参数为-1表示Launcher不需要知道根Activity的启动结果
    4. if (options != null) {
    5. startActivityForResult(intent, -1, options);
    6. } else {
    7. // Note we want to go through this call for compatibility with
    8. // applications that may have overridden the method.
    9. startActivityForResult(intent, -1);
    10. }
    11. }
    12. public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
    13. startActivityForResult(intent, requestCode, null);
    14. }
    15. public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
    16. @Nullable Bundle options) {
    17. //mParent表示当前Activity的父类,当根活动还没创建则mParent==null
    18. if (mParent == null) {
    19. options = transferSpringboardActivityOptions(options);
    20. Instrumentation.ActivityResult ar =
    21. mInstrumentation.execStartActivity(
    22. this, mMainThread.getApplicationThread(), mToken, this,
    23. intent, requestCode, options);
    24. ...
    25. }
    26. ...
    27. }
    28. 复制代码

    从上面代码可以发现startActivity的最终实现是startActivityForResult,startActivity()第二个参数为-1表示Launcher不需要知道根Activity的启动结果,然后在startActivityForResult中由于此时根Activity还没有创建,故mParent=null,所以我们只需要关注mParent=null的情况。在这种情况中会调用Instrumentation的execStartActivity。这时候也许你就会问这个Instrumentation是什么?为什么要交给她弄呢?其实Instrumentation这个类很重要,重要体现在对Activity生命周期的调用根本离不开她。每个Activity都持有Instrumentation对象的一个引用,但是整个进程只会存在一个Instrumentation对象。回归正题,让我们瞧瞧Instrumentation的execStartActivity这个方法。

    frameworks/base/core/java/android/app/Instrumentation.java

    1. public ActivityResult execStartActivity(
    2. Context who, IBinder contextThread, IBinder token, Activity target,
    3. Intent intent, int requestCode, Bundle options) {
    4. ...
    5. try {
    6. ...
    7. //获取AMS的代理对象
    8. int result = ActivityManager.getService()
    9. .startActivity(whoThread, who.getBasePackageName(), intent,
    10. intent.resolveTypeIfNeeded(who.getContentResolver()),
    11. token, target != null ? target.mEmbeddedID : null,
    12. requestCode, 0, null, options);
    13. checkStartActivityResult(result, intent);
    14. } catch (RemoteException e) {
    15. throw new RuntimeException("Failure from system", e);
    16. }
    17. return null;
    18. }
    19. 复制代码

    在这个方法会调用ActivityManager的getService方法来得到AMS的代理对象,然后调用这个代理对象的

    startActivity方法,那么这个代理对象是谁呢?让我们一探究竟

    1. @UnsupportedAppUsage
    2. public static IActivityManager getService() {
    3. return IActivityManagerSingleton.get();
    4. }
    5. @UnsupportedAppUsage
    6. private static final Singleton<IActivityManager> IActivityManagerSingleton =
    7. new Singleton<IActivityManager>() {
    8. @Override
    9. protected IActivityManager create() {
    10. //得到activity的service引用,即IBinder类型的AMS引用
    11. final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
    12. //转换成IActivityManager对象
    13. final IActivityManager am = IActivityManager.Stub.asInterface(b);
    14. return am;
    15. }
    16. };
    17. 复制代码

    可以发现在Singleton中的create方法中由于b是AMS引用作为服务端处于SystemServer进程中,与当前Launcher进程作为客户端与服务端不在同一个进程,所以am返回的是IActivityManager.Stub的代理对象,此时如果要实现客户端与服务端进程间的通信,只需要在AMS继承了IActivityManager.Stub类并实现了相应的方法,而通过下面的代码可以发现AMS刚好是继承了IActivityManager.Stub类的,这样Launcher进程作为客户端就拥有了服务端AMS的代理对象,然后就可以调用AMS的方法来实现具体功能了,就这样Launcher的工作就交给AMS实现了。

    1. public class ActivityManagerService extends IActivityManager.Stub
    2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    3. }

    二、AMS发送创建应用进程请求

    通过上面的分析,我们已经知道现在任务已经交给了AMS,入口是AMS的startActivity。

    1. 时序图

    在这里插入图片描述

    2. 详细过程

    2.1 AMS将请求任务转移给Process

    首先来看看在AMS中的startActivity方法:

    源码:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    1. @Override
    2. public final int startActivity(IApplicationThread caller, String callingPackage,
    3. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
    4. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    5. return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
    6. resultWho, requestCode, startFlags, profilerInfo, bOptions,
    7. UserHandle.getCallingUserId());
    8. }
    9. @Override
    10. public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
    11. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
    12. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
    13. return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
    14. resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
    15. true /*validateIncomingUser*/);
    16. }
    17. public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
    18. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
    19. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
    20. boolean validateIncomingUser) {
    21. //判断调用者的进程是否隔离
    22. enforceNotIsolatedCaller("startActivity");
    23. //检查调用者权限
    24. userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
    25. Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    26. // TODO: Switch to user app stacks here.
    27. return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
    28. .setCaller(caller)
    29. .setCallingPackage(callingPackage)
    30. .setResolvedType(resolvedType)
    31. .setResultTo(resultTo)
    32. .setResultWho(resultWho)
    33. .setRequestCode(requestCode)
    34. .setStartFlags(startFlags)
    35. .setProfilerInfo(profilerInfo)
    36. .setActivityOptions(bOptions)
    37. .setMayWait(userId)
    38. .execute();
    39. }
    40. 复制代码

    startActivity方法经过多个方法调用会去执行startActivityAsUser方法,在startActivityAsUser方法最后会返回mActivityStartController的一长串链式调用方法,如果AlertDialog的话,应该不难看出这链式方法肯定都是返回一个类型的对象的,我们只需要看看obtainStarter的返回类型就可以知道这个对象是什么类型了。

    frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java

    1. ActivityStarter obtainStarter(Intent intent, String reason) {
    2. return mFactory.obtain().setIntent(intent).setReason(reason);
    3. }
    4. 复制代码

    可以发现这个obtainStarter返回的是ActivityStarter类型的,所以链式方法就是对ActivityStarter对象设置了要启动的活动的相关信息,最后再调用ActivityStarter对象execute方法。所以我们下一步所需要看的就是这个execute方法。

    frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

    1. int execute() {
    2. try {
    3. // TODO(b/64750076): Look into passing request directly to these methods to allow
    4. // for transactional diffs and preprocessing.
    5. if (mRequest.mayWait) {
    6. return startActivityMayWait(mRequest.caller, mRequest.callingUid,
    7. mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
    8. mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
    9. mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
    10. mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
    11. mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
    12. mRequest.inTask, mRequest.reason,
    13. mRequest.allowPendingRemoteAnimationRegistryLookup,
    14. mRequest.originatingPendingIntent);
    15. } else {
    16. return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
    17. mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
    18. mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
    19. mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
    20. mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
    21. mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
    22. mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
    23. mRequest.outActivity, mRequest.inTask, mRequest.reason,
    24. mRequest.allowPendingRemoteAnimationRegistryLookup,
    25. mRequest.originatingPendingIntent);
    26. }
    27. } finally {
    28. onExecutionComplete();
    29. }
    30. }
    31. 复制代码

    因为在startActivityAsUser的链式方法中我们调用了setMayWait这个方法,所以这里的mRequest.mayWait为true,故会继续调用startActivityMayWait方法。

    ActivityStarter#startActivityMayWait

    1. private int startActivityMayWait(IApplicationThread caller, int callingUid,
    2. String callingPackage, Intent intent, String resolvedType,
    3. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    4. IBinder resultTo, String resultWho, int requestCode, int startFlags,
    5. ProfilerInfo profilerInfo, WaitResult outResult,
    6. Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
    7. int userId, TaskRecord inTask, String reason,
    8. boolean allowPendingRemoteAnimationRegistryLookup,
    9. PendingIntentRecord originatingPendingIntent) {
    10. .....
    11. //根据intent在系统中找到合适的应用的activity,如果有多个activity可选择,
    12. //则会弹出ResolverActivity让用户选择合适的应用。
    13. ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    14. int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
    15. voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
    16. callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
    17. ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
    18. allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent);
    19. ....
    20. }
    21. private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
    22. String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
    23. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    24. IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
    25. String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
    26. SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
    27. ActivityRecord[] outActivity, TaskRecord inTask, String reason,
    28. boolean allowPendingRemoteAnimationRegistryLookup) {
    29. ...
    30. mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
    31. aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
    32. callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
    33. options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
    34. inTask, allowPendingRemoteAnimationRegistryLookup);
    35. ...
    36. return getExternalResult(mLastStartActivityResult);
    37. }
    38. private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
    39. String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
    40. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    41. IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
    42. String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
    43. SafeActivityOptions options,
    44. boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
    45. TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
    46. ...
    47. return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
    48. true /* doResume */, checkedOptions, inTask, outActivity);
    49. }
    50. private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
    51. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    52. int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
    53. ActivityRecord[] outActivity) {
    54. ...
    55. result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
    56. startFlags, doResume, options, inTask, outActivity);
    57. ...
    58. postStartActivityProcessing(r, result, mTargetStack);
    59. return result;
    60. }
    61. 复制代码

    startActivityMayWait方法经过调用多次的startActivity方法后会调用到startActivityUnchecked这个方法,那这个方法是干啥的呢?这个方法会根据启动标志位和Activity启动模式来决定如何启动一个Activity以及是否要调用deliverNewIntent方法通知Activity有一个Intent试图重新启动它。比如我们在一开始将活动设置了FLAG_ACTIVITY_NEW_TASK后将创建一个任务栈,其它的就自行看代码。

    1. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
    2. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
    3. int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
    4. ActivityRecord[] outActivity) {
    5. ...
    6. if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
    7. && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
    8. newTask = true;
    9. //创建新的TaskRecord
    10. result = setTaskFromReuseOrCreateNewTask(
    11. taskToAffiliate, preferredLaunchStackId, topStack);
    12. } else if (mSourceRecord != null) {
    13. result = setTaskFromSourceRecord();
    14. } else if (mInTask != null) {
    15. result = setTaskFromInTask();
    16. } else {
    17. setTaskToCurrentTopOrCreateNewTask();
    18. }
    19. ...
    20. if (mDoResume) {
    21. final ActivityRecord topTaskActivity =
    22. mStartActivity.getTask().topRunningActivityLocked();
    23. if (!mTargetStack.isFocusable()
    24. || (topTaskActivity != null && topTaskActivity.mTaskOverlay
    25. && mStartActivity != topTaskActivity)) {
    26. ...
    27. } else {
    28. if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
    29. mTargetStack.moveToFront("startActivityUnchecked");
    30. }
    31. mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
    32. mOptions);
    33. }
    34. } else {
    35. mTargetStack.addRecentActivityLocked(mStartActivity);
    36. }
    37. ...
    38. }
    39. 复制代码

    然后无论以何种模式启动最终都会调用ActivityStackSupervisor.resumeFocusedStackTopActivityLocked方法。

    frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

    1. boolean resumeFocusedStackTopActivityLocked(
    2. ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    3. ....
    4. if (targetStack != null && isFocusedStack(targetStack)) {
    5. return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    6. }
    7. ....
    8. }
    9. 复制代码

    于是又调用了ActivityStack的resumeTopActivityUncheckedLocked

    frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

    1. @GuardedBy("mService")
    2. boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    3. ...
    4. try {
    5. // Protect against recursion.
    6. mStackSupervisor.inResumeTopActivity = true;
    7. result = resumeTopActivityInnerLocked(prev, options);
    8. }
    9. ...
    10. }
    11. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    12. ...
    13. mStackSupervisor.startSpecificActivityLocked(next, true, true);
    14. }
    15. if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    16. return true;
    17. }
    18. 复制代码

    emmmm.....,看到这估计都懵逼了,几个类跳来跳去也不知道干了些什么,不慌,让我们坚持看下ActivityStackSupervisor.startSpecificActivityLocked,因为这个方法很重要。这个方法将是普通Activity和根Activity启动流程的分岔路口。

    ActivityStackSupervisor#startSpecificActivityLocked

    1. void startSpecificActivityLocked(ActivityRecord r,
    2. boolean andResume, boolean checkConfig) {
    3. //获取即将要启动的Activity的所在的应用程序进程
    4. ProcessRecord app = mService.getProcessRecordLocked(r.processName,
    5. r.info.applicationInfo.uid, true);
    6. //如果应用进程已经存在
    7. if (app != null && app.thread != null) {
    8. try {
    9. if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
    10. || !"android".equals(r.info.packageName)) {
    11. // Don't add this if it is a platform component that is marked
    12. // to run in multiple processes, because this is actually
    13. // part of the framework so doesn't make sense to track as a
    14. // separate apk in the process.
    15. app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
    16. mService.mProcessStats);
    17. }
    18. realStartActivityLocked(r, app, andResume, checkConfig);
    19. return;
    20. } catch (RemoteException e) {
    21. Slog.w(TAG, "Exception when starting activity "
    22. + r.intent.getComponent().flattenToShortString(), e);
    23. }
    24. // If a dead object exception was thrown -- fall through to
    25. // restart the application.
    26. }
    27. //应用进程还未创建,则通过AMS调用startProcessLocked向Zygote进程发送请求
    28. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
    29. "activity", r.intent.getComponent(), false, false, true);
    30. }
    31. 复制代码

    阅读上面的代码我们可以知道在方法中首先获取到了即将要启动的Activity所在的应用进程,假如是普通的Activity的启动流程的活,这个进程肯定是存在的,所以将执行realStartActivityLocked的方法。但是我们现在讨论的是根Activity的启动流程,由于应用都还未启动,意味着根Activity所在的应用进程还未创建,而mService其实就是AMS,所以这里将调用AMS的startProcessLocked。于是我们又回到了最初的起点AMS。

    ActivityManagerService.java

    1. final ProcessRecord startProcessLocked(String processName,
    2. ApplicationInfo info, boolean knownToBeDead, int intentFlags,
    3. String hostingType, ComponentName hostingName, boolean allowWhileBooting,
    4. boolean isolated, boolean keepIfLarge) {
    5. return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
    6. hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
    7. null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
    8. null /* crashHandler */);
    9. }
    10. final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
    11. boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
    12. boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
    13. String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    14. ...
    15. final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
    16. ...
    17. }
    18. @GuardedBy("this")
    19. private final boolean startProcessLocked(ProcessRecord app,
    20. String hostingType, String hostingNameStr, String abiOverride) {
    21. return startProcessLocked(app, hostingType, hostingNameStr,
    22. false /* disableHiddenApiChecks */, abiOverride);
    23. }
    24. private final boolean startProcessLocked(ProcessRecord app, String hostingType,
    25. String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
    26. ...
    27. int uid = app.uid; //创建应用进程的用户ID
    28. int[] gids = null;
    29. int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
    30. if (!app.isolated) {
    31. int[] permGids = null;
    32. try {
    33. checkTime(startTime, "startProcess: getting gids from package manager");
    34. final IPackageManager pm = AppGlobals.getPackageManager();
    35. permGids = pm.getPackageGids(app.info.packageName,
    36. MATCH_DEBUG_TRIAGED_MISSING, app.userId);
    37. StorageManagerInternal storageManagerInternal = LocalServices.getService(
    38. StorageManagerInternal.class);
    39. mountExternal = storageManagerInternal.getExternalStorageMountMode(uid,
    40. app.info.packageName);
    41. } catch (RemoteException e) {
    42. throw e.rethrowAsRuntimeException();
    43. }
    44. /*
    45. * 对用户组进行创建和赋值
    46. */
    47. if (ArrayUtils.isEmpty(permGids)) {
    48. gids = new int[3];
    49. } else {
    50. gids = new int[permGids.length + 3];
    51. System.arraycopy(permGids, 0, gids, 3, permGids.length);
    52. }
    53. gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
    54. gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid));
    55. gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid));
    56. // Replace any invalid GIDs
    57. if (gids[0] == UserHandle.ERR_GID) gids[0] = gids[2];
    58. if (gids[1] == UserHandle.ERR_GID) gids[1] = gids[2];
    59. }
    60. ...
    61. //这个参数后文会提到
    62. final String entryPoint = "android.app.ActivityThread";
    63. return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
    64. runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
    65. startTime);
    66. }
    67. private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
    68. ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
    69. String seInfo, String requiredAbi, String instructionSet, String invokeWith,
    70. long startTime) {
    71. ....
    72. //重点关注
    73. final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
    74. app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
    75. requiredAbi, instructionSet, invokeWith, app.startTime);
    76. ...
    77. }
    78. private ProcessStartResult startProcess(String hostingType, String entryPoint,
    79. ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
    80. String seInfo, String requiredAbi, String instructionSet, String invokeWith,
    81. long startTime) {
    82. ....
    83. if (hostingType.equals("webview_service")) {
    84. startResult = startWebView(entryPoint,
    85. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
    86. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
    87. app.info.dataDir, null,
    88. new String[] {PROC_START_SEQ_IDENT + app.startSeq});
    89. } else {
    90. //通过Process.start方法来为应用创建进程
    91. startResult = Process.start(entryPoint,
    92. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
    93. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
    94. app.info.dataDir, invokeWith,
    95. new String[] {PROC_START_SEQ_IDENT + app.startSeq});
    96. }
    97. checkTime(startTime, "startProcess: returned from zygote!");
    98. return startResult;
    99. } finally {
    100. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    101. }
    102. }
    103. 复制代码

    是不是又惊呆了,好吧,我也惊呆了!反正就是通过调用多个startProcessLocked方法后最终将调用startProcess方法,不过需要重点看一下上面的第四个startProcessLocked,在该方法中有个entryPoint参数为 "android.app.ActivityThread",这个参数将在后文讲到创建应用进程后启动ActivityThread会用到。然后在startProcess方法里将调用Process.start来发送应用创建进程的请求。这样AMS就将发送请求的事交给了Process

    2.2 Process向Zygote进程发送创建应用进程请求

    frameworks/base/core/java/android/os/Process.java

    1. public static final ProcessStartResult start(final String processClass,
    2. final String niceName,
    3. int uid, int gid, int[] gids,
    4. int runtimeFlags, int mountExternal,
    5. int targetSdkVersion,
    6. String seInfo,
    7. String abi,
    8. String instructionSet,
    9. String appDataDir,
    10. String invokeWith,
    11. String[] zygoteArgs) {
    12. return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
    13. runtimeFlags, mountExternal, targetSdkVersion, seInfo,
    14. abi, instructionSet, appDataDir, invokeWith,
    15. /*useBlastulaPool=*/ true, zygoteArgs);
    16. }
    17. public final Process.ProcessStartResult start(final String processClass,
    18. final String niceName,
    19. int uid, int gid, int[] gids,
    20. int runtimeFlags, int mountExternal,
    21. int targetSdkVersion,
    22. String seInfo,
    23. String abi,
    24. String instructionSet,
    25. String appDataDir,
    26. String invokeWith,
    27. boolean useBlastulaPool,
    28. String[] zygoteArgs) {
    29. try {
    30. //重点关注
    31. return startViaZygote(processClass, niceName, uid, gid, gids,
    32. runtimeFlags, mountExternal, targetSdkVersion, seInfo,
    33. abi, instructionSet, appDataDir, invokeWith,
    34. /*startChildZygote=*/false,
    35. useBlastulaPool, zygoteArgs);
    36. } catch (ZygoteStartFailedEx ex) {
    37. Log.e(LOG_TAG,
    38. "Starting VM process through Zygote failed");
    39. throw new RuntimeException(
    40. "Starting VM process through Zygote failed", ex);
    41. }
    42. }
    43. 复制代码

    从上面可以发现,Process中的start方法的实现是startViaZygote方法,所以我们重点观察下这个方法。

    1. private Process.ProcessStartResult startViaZygote(final String processClass,
    2. final String niceName,
    3. final int uid, final int gid,
    4. final int[] gids,
    5. int runtimeFlags, int mountExternal,
    6. int targetSdkVersion,
    7. String seInfo,
    8. String abi,
    9. String instructionSet,
    10. String appDataDir,
    11. String invokeWith,
    12. boolean startChildZygote,
    13. boolean useBlastulaPool,
    14. String[] extraArgs)
    15. throws ZygoteStartFailedEx {
    16. ArrayList<String> argsForZygote = new ArrayList<String>();
    17. // --runtime-args, --setuid=, --setgid=,
    18. //创建字符串列表argsForZygote,并将启动应用进程的启动参数保存在这个列表中
    19. argsForZygote.add("--runtime-args");
    20. argsForZygote.add("--setuid=" + uid);
    21. argsForZygote.add("--setgid=" + gid);
    22. argsForZygote.add("--runtime-flags=" + runtimeFlags);
    23. if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
    24. argsForZygote.add("--mount-external-default");
    25. } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
    26. argsForZygote.add("--mount-external-read");
    27. } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
    28. argsForZygote.add("--mount-external-write");
    29. }
    30. argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
    31. ...
    32. synchronized(mLock) {
    33. //重点关注
    34. return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
    35. useBlastulaPool,
    36. argsForZygote);
    37. }
    38. }
    39. 复制代码

    在startViaZygote中会创建字符串列表argsForZygote来保存将要创建的应用进程的启动参数,然后最后会调用zygoteSendArgsAndGetResult方法,而在这个方法中第一个参数会调用openZygoteSocketIfNeeded方法,第三个参数就是启动参数列表。所以我们先看看openZygoteSocketIfNeeded这个方法的实现。

    1. private ZygoteState openZygoteSocketIfNeeded(String abi)
    2. throws ZygoteStartFailedEx {
    3. Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
    4. //64位进程中的
    5. if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
    6. try {
    7. //调用ZygoteState的connect函数与mZygoteSocketAddress建立连接,
    8. //这里mZygoteSocketAddress的值为“zygote”
    9. primaryZygoteState =
    10. ZygoteState.connect(mZygoteSocketAddress, mBlastulaPoolSocketAddress);
    11. } catch (IOException ioe) {
    12. throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
    13. }
    14. maybeSetApiBlacklistExemptions(primaryZygoteState, false);
    15. maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
    16. }
    17. if (primaryZygoteState.matches(abi)) {
    18. //Socket进行连接成功并匹配abi后会返回ZygoteState类型对象
    19. return primaryZygoteState;
    20. }
    21. // 32位Zygote进程中
    22. if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
    23. try {
    24. secondaryZygoteState =
    25. ZygoteState.connect(mZygoteSecondarySocketAddress,
    26. mBlastulaPoolSecondarySocketAddress);
    27. } catch (IOException ioe) {
    28. throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
    29. }
    30. maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
    31. maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
    32. }
    33. if (secondaryZygoteState.matches(abi)) {
    34. return secondaryZygoteState;
    35. }
    36. throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
    37. }
    38. 复制代码

    openZygoteSocketIfNeeded这个方法从方法名就可以推测出这个方法的作用,大概就是与Zygote建立Socket连接。而从代码中也证实了这一点,在代码中会根据Zygote进程的位数来建立相应的Socket连接,然后返回ZygoteState类型的对象。既然与Zygote建立好Socket连接后,接下来当然是发送请求啦!所以让我们来看看zygoteSendArgsAndGetResult这个方法中是如何发送请求的!

    1. //将传入的应用进程的启动参数argsForZygote写入到ZygoteState
    2. @GuardedBy("mLock")
    3. private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
    4. ZygoteState zygoteState, boolean useBlastulaPool, ArrayList<String> args)
    5. throws ZygoteStartFailedEx {
    6. String msgStr = Integer.toString(args.size()) + "\n"
    7. + String.join("\n", args) + "\n";
    8. // Should there be a timeout on this?
    9. Process.ProcessStartResult result = new Process.ProcessStartResult();
    10. // TODO (chriswailes): Move branch body into separate function.
    11. if (useBlastulaPool && Zygote.BLASTULA_POOL_ENABLED && isValidBlastulaCommand(args)) {
    12. LocalSocket blastulaSessionSocket = null;
    13. try {
    14. blastulaSessionSocket = zygoteState.getBlastulaSessionSocket();
    15. final BufferedWriter blastulaWriter =
    16. new BufferedWriter(
    17. new OutputStreamWriter(blastulaSessionSocket.getOutputStream()),
    18. Zygote.SOCKET_BUFFER_SIZE);
    19. final DataInputStream blastulaReader =
    20. new DataInputStream(blastulaSessionSocket.getInputStream());
    21. blastulaWriter.write(msgStr);
    22. blastulaWriter.flush();
    23. result.pid = blastulaReader.readInt();
    24. // Blastulas can't be used to spawn processes that need wrappers.
    25. result.usingWrapper = false;
    26. if (result.pid < 0) {
    27. throw new ZygoteStartFailedEx("Blastula specialization failed");
    28. }
    29. return result;
    30. } catch (IOException ex) {
    31. // If there was an IOException using the blastula pool we will log the error and
    32. // attempt to start the process through the Zygote.
    33. Log.e(LOG_TAG, "IO Exception while communicating with blastula pool - "
    34. + ex.toString());
    35. } finally {
    36. try {
    37. blastulaSessionSocket.close();
    38. } catch (IOException ex) {
    39. Log.e(LOG_TAG, "Failed to close blastula session socket: " + ex.getMessage());
    40. }
    41. }
    42. }
    43. try {
    44. final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
    45. final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
    46. zygoteWriter.write(msgStr);
    47. zygoteWriter.flush();
    48. // Always read the entire result from the input stream to avoid leaving
    49. // bytes in the stream for future process starts to accidentally stumble
    50. // upon.
    51. result.pid = zygoteInputStream.readInt();
    52. result.usingWrapper = zygoteInputStream.readBoolean();
    53. } catch (IOException ex) {
    54. zygoteState.close();
    55. Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
    56. + ex.toString());
    57. throw new ZygoteStartFailedEx(ex);
    58. }
    59. if (result.pid < 0) {
    60. throw new ZygoteStartFailedEx("fork() failed");
    61. }
    62. return result;
    63. }
    64. 复制代码

    因为在openZygoteSocketIfNeeded中我们已经与Zygote进程建立了Socket连接,所以在这个方法中将传入的应用进程的启动参数argsForZygote写入到ZygoteState。这样AMS就完成了向Zygote进程发送创建应用进程的请求的任务。

    三、Zygote进程接受请求并孵化应用进程

    从上面我们知道,AMS已经与Zygote进程建立Socket连接并发送了创建应用进程的请求,那么Zygote进程是在哪里收到请求,收到请求后又是怎么处理的呢?这里可以停下来先看看刘望舒的Android系统启动流程(二)解析Zygote进程启动过程,写的很不错。不过由于我们分析的源码基于8.0,可能会稍微不同,但总体上来大致流程是一样的。通过阅读后我们知道Zygote进程是在ZygoteInit的main方法中接受请求的。所以现在的入口就是ZygoteInit的main方法。

    1. 时序图

    在这里插入图片描述

    2. 详细过程

    从时序图与上面的分析我们知道现在Zygote进程接受请求是在main方法,就让我们来看看这个main方法

    frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

    1. @UnsupportedAppUsage
    2. public static void main(String argv[]) {
    3. ZygoteServer zygoteServer = new ZygoteServer();
    4. Runnable caller;
    5. try {
    6. ...
    7. //创建名为zygote的Socket
    8. zygoteServer.createZygoteSocket(socketName);
    9. ....
    10. //由于在init.rc中设置了start-system-server参数,因此
    11. //这里将启动SystemServer,可见SystemServer由Zygote创建的第一个进程
    12. if (startSystemServer) {
    13. Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
    14. if (r != null) {
    15. r.run();
    16. return;
    17. }
    18. }
    19. caller = Zygote.initBlastulaPool();
    20. if (caller == null) {
    21. Log.i(TAG, "Accepting command socket connections");
    22. //等待AMS的请求
    23. caller = zygoteServer.runSelectLoop(abiList);
    24. }
    25. } catch (Throwable ex) {
    26. Log.e(TAG, "System zygote died with exception", ex);
    27. throw ex;
    28. } finally {
    29. zygoteServer.closeServerSocket();
    30. }
    31. // We're in the child process and have exited the select loop. Proceed to execute the
    32. // command.
    33. if (caller != null) {
    34. caller.run();
    35. }
    36. }
    37. 复制代码

    通过main方法,我们可以知道在这个main方法首先要创建一个Server端的Socket,这个name为”zygote”的Socket用来等待ActivityManagerService来请求Zygote来创建新的应用程序进程,在上面AMS请求的分析中我们也知道客户端将根据这个name来与Zygote的Socket建立连接。接下去会启动SystemServer进程,这个进程会启动各种系统服务,比如与Activity启动息息相关的AMS。最后会调用ZygoteServer.runSelectLoop(abiList)来使创建的Socket进入无限循环,等待AMS请求。让我们来看看这个runSelectLoop

    frameworks/base/core/java/com/android/internal/os/ZygoteServer.java

    1. Runnable runSelectLoop(String abiList) {
    2. ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
    3. peers.add(null);
    4. while (true) {
    5. while (--pollIndex >= 0) {
    6. if ((pollFDs[pollIndex].revents & POLLIN) == 0) {
    7. continue;
    8. }
    9. if (pollIndex == 0) {
    10. //监听Socket连接,充当服务端Socket
    11. ZygoteConnection newPeer = acceptCommandPeer(abiList);
    12. peers.add(newPeer);
    13. socketFDs.add(newPeer.getFileDescriptor());
    14. } else if (pollIndex < blastulaPoolEventFDIndex) {
    15. try {
    16. //不断处理客户端的AMS的请求,然后交给processOneCommand
    17. ZygoteConnection connection = peers.get(pollIndex);
    18. final Runnable command = connection.processOneCommand(this);
    19. }
    20. ....
    21. }
    22. }
    23. }
    24. }
    25. 复制代码

    可以发现这个方法是死循环表示不停的监听着Socket连接。acceptCommandPeer方法就是监听是否收到了请求,如果收到了请求就交给processOneCommand来实现

    frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

    1. Runnable processOneCommand(ZygoteServer zygoteServer) {
    2. String args[];
    3. ZygoteArguments parsedArgs = null;
    4. FileDescriptor[] descriptors;
    5. try {
    6. //获取应用程序进程的启动参数
    7. args = Zygote.readArgumentList(mSocketReader);
    8. // TODO (chriswailes): Remove this and add an assert.
    9. descriptors = mSocket.getAncillaryFileDescriptors();
    10. } catch (IOException ex) {
    11. throw new IllegalStateException("IOException on command socket", ex);
    12. }
    13. ....
    14. parsedArgs = new ZygoteArguments(args);
    15. ....
    16. //fork当前进程创建一个子进程
    17. pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
    18. parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
    19. parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
    20. parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
    21. try {
    22. //pid为0则代表这个进程为子进程,即新创建的应用程序进程
    23. if (pid == 0) {
    24. zygoteServer.setForkChild();
    25. zygoteServer.closeServerSocket();
    26. IoUtils.closeQuietly(serverPipeFd);
    27. serverPipeFd = null;
    28. return handleChildProc(parsedArgs, descriptors, childPipeFd,
    29. parsedArgs.mStartChildZygote);
    30. } else {
    31. // In the parent. A pid < 0 indicates a failure and will be handled in
    32. // handleParentProc.
    33. IoUtils.closeQuietly(childPipeFd);
    34. childPipeFd = null;
    35. handleParentProc(pid, descriptors, serverPipeFd);
    36. return null;
    37. }
    38. } finally {
    39. IoUtils.closeQuietly(childPipeFd);
    40. IoUtils.closeQuietly(serverPipeFd);
    41. }
    42. }
    43. 复制代码

    在这个方法中将对请求进行处理,首先获取到将要启动的应用进程的启动参数,然后调用forkAndSpecialize来创建应用进程。

    frameworks/base/core/java/com/android/internal/os/Zygote.java

    1. public static int forkAndSpecialize(int uid, int gid, int[] gids, int runtimeFlags,
    2. int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
    3. int[] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir,
    4. int targetSdkVersion) {
    5. ZygoteHooks.preFork();
    6. // Resets nice priority for zygote process.
    7. resetNicePriority();
    8. int pid = nativeForkAndSpecialize(
    9. uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
    10. fdsToIgnore, startChildZygote, instructionSet, appDataDir);
    11. // Enable tracing as soon as possible for the child process.
    12. if (pid == 0) {
    13. Zygote.disableExecuteOnly(targetSdkVersion);
    14. Trace.setTracingEnabled(true, runtimeFlags);
    15. // Note that this event ends at the end of handleChildProc,
    16. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
    17. }
    18. ZygoteHooks.postForkCommon();
    19. return pid;
    20. }
    21. 复制代码

    在forkAndSpecialize中,最终将创建应用进程的任务交给nativeForkAndSpecialize,而这个方法可以看出来应该是本地方法,所以具体如何创建的我们就不深究了,在这里我们这需要知道nativeForkAndSpecialize最终是通过fork当前进程来创建一个子进程,而fork后会有返回值给pid:

  • 父进程中,fork返回新创建的子进程pid;
  • 子进程中,fork返回0;
  • 出现错误时,fork返回负数。

四、应用进程启动ActivityThread

1. 时序图

在这里插入图片描述

2. 详细过程

从上面我们知道应用进程已经被创建,那创建后呢?这就需要我们回头看上面的processOneCommand方法,细心的你肯定会发现再孵化出应用进程后,还是有返回值的。

frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

  1. Runnable processOneCommand(ZygoteServer zygoteServer) {
  2. ....
  3. //fork当前进程创建一个子进程
  4. pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
  5. parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
  6. parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
  7. parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
  8. try {
  9. //pid为0则代表这个进程为子进程,即新创建的应用程序进程
  10. if (pid == 0) {
  11. ....
  12. return handleChildProc(parsedArgs, descriptors, childPipeFd,
  13. parsedArgs.mStartChildZygote);
  14. } else {
  15. ...
  16. }
  17. }
  18. ....
  19. }
  20. 复制代码

在上面我们分析了当pid=0的时候,则代表了当前进程已经是子进程了,即应用进程。所以下一步将执行handleChildProc方法。

  1. private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor[] descriptors,
  2. FileDescriptor pipeFd, boolean isZygote) {
  3. .....
  4. if (!isZygote) {
  5. return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
  6. parsedArgs.mRemainingArgs, null /* classLoader */);
  7. } else {
  8. ....
  9. }
  10. }
  11. 复制代码

而handleChildProc最终又会调用ZygoteInit.zygoteInit方法。如下

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

  1. public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
  2. ClassLoader classLoader) {
  3. if (RuntimeInit.DEBUG) {
  4. Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
  5. }
  6. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
  7. RuntimeInit.redirectLogStreams();
  8. //为当前的VM设置未捕获异常器
  9. RuntimeInit.commonInit();
  10. //Binder驱动初始化,该方法完成后,可通过Binder进行进程通信
  11. ZygoteInit.nativeZygoteInit();
  12. //主要调用SystemServer的main方法
  13. return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
  14. }
  15. 复制代码

在这个方法里会创建当前进程的Binder线程池,便于后续与其它进程通信,然后调用了RuntimeInit的applicationInit方法,如下:

frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

  1. protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
  2. ClassLoader classLoader) {
  3. ...
  4. final Arguments args = new Arguments(argv);
  5. // Remaining arguments are passed to the start class's static main
  6. return findStaticMain(args.startClass, args.startArgs, classLoader);
  7. }
  8. 复制代码

这个方法最终会调用findStaticMain方法,不过需注意的是方法的第一个参数args.startClass其实就是我们上文AMS将请求任务转移给Process中在最后强调的那个参数:android.app.ActivityThread。然后我们看看findStaticMain的实现

  1. protected static Runnable findStaticMain(String className, String[] argv,
  2. ClassLoader classLoader) {
  3. Class<?> cl;
  4. try {
  5. cl = Class.forName(className, true, classLoader);//1
  6. } catch (ClassNotFoundException ex) {
  7. ....
  8. }
  9. Method m;
  10. try {
  11. m = cl.getMethod("main", new Class[] { String[].class });//2
  12. } catch (NoSuchMethodException ex) {
  13. ...
  14. } catch (SecurityException ex) {
  15. ...
  16. }
  17. return new MethodAndArgsCaller(m, argv);
  18. }
  19. 复制代码

在这个方法中首先在注释1通过反射获取到android.app.ActivityThread类,然后在注释2获取到ActivityThread的main方法,最后通过main方法来构造MethodAndArgsCaller。而这个MethodAndArgsCaller是什么呢?如下:

frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

  1. static class MethodAndArgsCaller implements Runnable {
  2. /** method to call */
  3. private final Method mMethod;
  4. /** argument array */
  5. private final String[] mArgs;
  6. public MethodAndArgsCaller(Method method, String[] args) {
  7. mMethod = method;
  8. mArgs = args;
  9. }
  10. public void run() {
  11. try {
  12. mMethod.invoke(null, new Object[] { mArgs });
  13. } catch (IllegalAccessException ex) {
  14. throw new RuntimeException(ex);
  15. } catch (InvocationTargetException ex) {
  16. Throwable cause = ex.getCause();
  17. if (cause instanceof RuntimeException) {
  18. throw (RuntimeException) cause;
  19. } else if (cause instanceof Error) {
  20. throw (Error) cause;
  21. }
  22. throw new RuntimeException(ex);
  23. }
  24. }
  25. }
  26. 复制代码

追踪下去,MethodAndArgsCaller其实是RuntimeInit的一个内部类并且继承了Runnable,然后在run方法中会通过反射调用了mMethod方法,此时mMethod是ActivityThread的main方法,即run方法中将会执行ActivityThread的main方法,在这里你可能会有疑问了,那这个run方法什么时候执行呢?让我们来看看最开始的ZygoteInit的main方法。

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

  1. @UnsupportedAppUsage
  2. public static void main(String argv[]) {
  3. Runnable caller;
  4. try {
  5. ....
  6. caller = Zygote.initBlastulaPool();
  7. if (caller == null) {
  8. Log.i(TAG, "Accepting command socket connections");
  9. //等待AMS的请求
  10. caller = zygoteServer.runSelectLoop(abiList);
  11. }
  12. } catch (Throwable ex) {
  13. Log.e(TAG, "System zygote died with exception", ex);
  14. throw ex;
  15. } finally {
  16. zygoteServer.closeServerSocket();
  17. }
  18. if (caller != null) {
  19. caller.run();
  20. }
  21. }
  22. 复制代码

有没有恍然大悟呢?从分析Zygote进程接受请求并孵化应用进程的一开始,我们就是分析zygoteServer.runSelectLoop(abiList)这个方法,而分析到最后findStaticMain方法将返回MethodAndArgsCaller对象(继承Runnable),所以这时候在ZygoteInit的main方法caller会等于这个MethodAndArgsCaller对象,显然caller不等于null,故最后会执行caller.run方法,即执行ActivityThread的main方法。于是应用进程成功启动ActivityThread。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号