当前位置:   article > 正文

Android Activity启动流程(基于Android8.0系统)

android8.0 app启动流程
主要对象介绍
  • ActivityManagerService:负责系统中所有Activity的生命周期;
  • ActivityThread:App的真正入口,当App启动后,会调用其main方法开始执行,开启消息循环队列。是传说中的UI线程,即主线程。与ActivityManagerService配合,一起完成Activity的管理工作;
  • ApplicationThread:用来实现ActivityManagerService与ActivityThread之间的交互。在ActivityManagerService需要管理相关Application中的Activity的生命周期,通过ApplicationThread的代理对象与ActivityThread通讯;
  • ApplictationThreadProxy:是ApplicationThread在服务端的代理对象,负责和客户端的ApplicationThread通讯。AMS就是通过这个代理对象与ActivityThread进行通信的,Android 8.0上以删除该类,采用AIDL接口的方式来进行IPC,实现RPC操作
  • Instrumentation:每一个应用程序都只有一个Instrumentation对象,每个Activity内都有一个对该对象的引用。Instrumentation可以理解为应用进程的管家,ActivityThread要创建或者打开某个Activity时,都需要通过Instrumentation来进行具体的操作;
  • ActvitityStack:Activity在AMS的栈管理,用来记录已经启动的Activity的先后关系、状态信息等。通过ActivityStack决定是否需要启动新的进程;
  • ActivityRecord:ActivityStatck的管理对象,每个Activity在AMS对应的一个ActivityRecord,来记录Activity的状态以及其他信息。可以理解为Activity在服务端的Activity对象的映射;
  • ActivityClientRecord:与ActivityRecord是在服务端(AMS)的记录相对应,是Activity在客户端(ActivityThread)的记录;
  • TaskRecord:AMS抽象出来的任务栈的概念。一个TaskRecord包含若干个ActivityRecord。ASM用它来确保Activity启动和退出顺序。它与Activity的启动模式直接相关。
  • ActivityStarter:启动Activity的控制器,主要用于用来将Intent和flags转换成activity和相关任务栈;
  • ActivityStackSupervisor:主要管理着mHomeStack和mFocusedStack两个ActivityStack等相关信息;
Binder通信
  • 在Android 8.0以前,Binder通信的流程如下:
    客户端: ActivityManagerProxy -> Binder驱动 -> 服务端:ActivityManagerService
    服务端: ApplicationThreadProxy -> Binder驱动 -> 客户端:ApplicationThread
  • Android8.0开始,删除了ActivityManagerNative,AMS的继承类也发生了变化,继承了IActivityManager.Stub接口类。了解Android的Binder机制应该知道,这里IActivityManager.aidl生成的接口类。Android8.0开始,把一些Binder代码转化为了AIDL模板方式:
  1. public class ActivityManagerService extends IActivityManager.Stub
  2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback

ActivityManager中的代码:

  1. public static IActivityManager getService() {
  2. return IActivityManagerSingleton.get();
  3. }
  4. private static final Singleton<IActivityManager> IActivityManagerSingleton =
  5. new Singleton<IActivityManager>() {
  6. @Override
  7. protected IActivityManager create() {
  8. final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
  9. final IActivityManager am = IActivityManager.Stub.asInterface(b);
  10. return am;
  11. }
  12. };
  • 而在Android7.0及其以前的版本上,则是客户端通过ActivityManaagerProxy与服务端的ActivityManager进行通信的
    ActivityManagerNative:
  1. **
  2. *获得IActivityManager类
  3. */
  4. static public IActivityManager getDefault() {
  5. return gDefault.get();
  6. }
  7. static public IActivityManager asInterface(IBinder obj) {
  8. if (obj == null) {
  9. return null;
  10. }
  11. IActivityManager in =
  12. (IActivityManager)obj.queryLocalInterface(descriptor);
  13. if (in != null) {
  14. return in;
  15. }
  16. return new ActivityManagerProxy(obj);
  17. }

ActivityManager:

  1. private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
  2. protected IActivityManager create() {
  3. IBinder b = ServiceManager.getService("activity");
  4. if (false) {
  5. Log.v("ActivityManager", "default service binder = " + b);
  6. }
  7. IActivityManager am = asInterface(b);//注意这一行
  8. if (false) {
  9. Log.v("ActivityManager", "default service = " + am);
  10. }
  11. return am;
  12. }
  13. };

可以看出来,两个写法不一样,本质上都是一样的,Android 8.0可能使用了AIDL方式进行ipc。

  • 同理,ApplicationThread同上述一样做了更改:
  1. private class ApplicationThread extends IApplicationThread.Stub {
  2. ...
  3. }

所以在Android 8.0上不存在ActivityManagerProxy和ApplicationThreadProxy,而是采用了AIDL接口的方式来进行通信的。

源码调用栈(基于Android 8.0)

按照自上而下的调用栈的顺序进行调用,以类文件为单位来计步,方便大家去了解调用流程,主要涉及的几个源文件:Instumentation,ActivityMangerService,ActivityStack,ActivityStarter,ActivityStackSupervisor,ActivityThread,Activity等。

  1. Activity
  1. public void startActivity(Intent intent)
  2. public void startActivity(Intent intent, @Nullable Bundle options)
  3. public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
  4. @Nullable Bundle options)
  1. Intrumentation
  1. public ActivityResult execStartActivity(
  2. Context who, IBinder contextThread, IBinder token, Activity target,
  3. Intent intent, int requestCode, Bundle options){
  4. ...
  5. int result = ActivityManager.getService()
  6. .startActivity(whoThread, who.getBasePackageName(), intent,
  7. intent.resolveTypeIfNeeded(who.getContentResolver()),
  8. token, target != null ? target.mEmbeddedID : null,
  9. requestCode, 0, null, options);
  10. ...
  11. }
  1. ActivityManagerService
  1. public final int startActivity(IApplicationThread caller, String callingPackage,
  2. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  3. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
  4. ...
  5. return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
  6. resultWho, requestCode, startFlags, profilerInfo, bOptions,
  7. UserHandle.getCallingUserId());
  8. }
  9. public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
  10. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  11. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
  12. ...
  13. return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
  14. resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
  15. profilerInfo, null, null, bOptions, false, userId, null, "startActivityAsUser");
  16. }
  1. ActivityStarter
  1. final 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, Bundle bOptions, boolean ignoreTargetSecurity,
  7. int userId,askRecord inTask, String reason) {
  8. ...
  9. int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
  10. aInfo, rInfo, voiceSession, voiceInteractor,
  11. resultTo, resultWho, requestCode, callingPid,
  12. callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
  13. options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,
  14. reason);
  15. ...
  16. }
  17. int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
  18. String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
  19. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  20. IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
  21. String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
  22. ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
  23. ActivityRecord[] outActivity, TaskRecord inTask, String reason) {
  24. ...
  25. mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
  26. aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
  27. callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
  28. options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
  29. inTask);
  30. ...
  31. }
  32. private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
  33. String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
  34. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  35. IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
  36. String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
  37. ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
  38. ActivityRecord[] outActivity, TaskRecord inTask) {
  39. ...
  40. doPendingActivityLaunchesLocked(false);
  41. return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
  42. options, inTask, outActivity);
  43. }
  44. private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
  45. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  46. int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
  47. ActivityRecord[] outActivity) {
  48. ...
  49. result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
  50. startFlags, doResume, options, inTask, outActivity);
  51. ...
  52. }
  53. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
  54. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  55. int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
  56. ActivityRecord[] outActivity) {
  57. ...
  58. if (mDoResume) {
  59. mSupervisor.resumeFocusedStackTopActivityLocked();
  60. }
  61. ...
  62. }
  1. ActivityStackSupervisor
  1. boolean resumeFocusedStackTopActivityLocked() {
  2. return resumeFocusedStackTopActivityLocked(null, null, null);
  3. }
  4. boolean resumeFocusedStackTopActivityLocked(
  5. ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  6. ...
  7. if (r == null || r.state != RESUMED) {
  8. mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
  9. }
  10. ...
  11. }
  1. ActivityStack
  1. boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
  2. ...
  3. result = resumeTopActivityInnerLocked(prev, options);
  4. ...
  5. }
  6. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  7. ....
  8. if (mResumedActivity != null) {
  9. //同步等待pause当前Activity的结果
  10. pausing |= startPausingLocked(userLeaving, false, next, false);
  11. }
  12. ....
  13. //开始启动下一个Activity
  14. mStackSupervisor.startSpecificActivityLocked(next, true, false);
  15. ....
  16. }
  17. final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, ActivityRecord resuming, boolean pauseImmediately) {
  18. ....
  19. //去当前Activity所在应用进程暂停当前activity
  20. prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
  21. userLeaving, prev.configChangeFlags, pauseImmediately);
  22. ....
  23. }
  1. ActivityThread$ApplicationThread
  1. public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) {
  2. ...
  3. sendMessage(finished ? H.PAUSE_ACTIVITY_FINISHING: H.PAUSE_ACTIVITY, token,
  4. (userLeaving ? USER_LEAVING: 0) | (dontReport ? DONT_REPORT: 0), configChanges, seq);
  5. ...
  6. }
  1. ActivityThread
  1. private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) {
  2. Message msg = Message.obtain();
  3. ....
  4. mH.sendMessage(msg);
  5. }
  1. ActivityThread$H
  1. public void handleMessage(Message msg) {
  2. ...
  3. switch (msg.what) {
  4. case PAUSE_ACTIVITY:
  5. {
  6. SomeArgs args = (SomeArgs) msg.obj;
  7. handlePauseActivity((IBinder) args.arg1, false, (args.argi1 & USER_LEAVING) != 0,
  8. args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3);
  9. }
  10. break;
  11. }
  12. ...
  13. }
  1. ActivityThread
  1. private void handlePauseActivity(IBinder token, boolean finished,
  2. boolean userLeaving, int configChanges, boolean dontReport, int seq) {
  3. ...
  4. performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");
  5. ...
  6. //执行完后通知AMS当前Activity已经pause
  7. ActivityManager.getService().activityPaused(token);
  8. ...
  9. }
  10. final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
  11. boolean saveState, String reason) {
  12. ...
  13. performPauseActivityIfNeeded(r, reason);
  14. ...
  15. }
  16. private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
  17. ...
  18. mInstrumentation.callActivityOnPause(r.activity);
  19. ...
  20. }
  1. Instrumentation
  1. public void callActivityOnPause(Activity activity) {
  2. activity.performPause();
  3. }
  1. Activity
  1. final void performPause() {
  2. ...
  3. onPause();
  4. ...
  5. }

由于在ActivityThread中handlePauseActivity的方法里,在pause成功后,需要通知AMS已经pause成功,所以接着分析ActivityManagerService.activityPaused方法。

  1. ActivityManagerService
  1. public final void activityPaused(IBinder token) {
  2. final long origId = Binder.clearCallingIdentity();
  3. synchronized(this) {
  4. ActivityStack stack = ActivityRecord.getStackLocked(token);
  5. if (stack != null) {
  6. stack.activityPausedLocked(token, false);
  7. }
  8. }
  9. Binder.restoreCallingIdentity(origId);
  10. }
  1. ActivityStack
  1. final void activityPausedLocked(IBinder token, boolean timeout) {
  2. ...
  3. mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
  4. ...
  5. completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
  6. ...
  7. }
  8. private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
  9. ...
  10. mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
  11. ...
  12. }
  1. ActivityStackSupervisor
  1. boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  2. //如果启动Activity和要启动的Activity在同一个ActivityStack中,调用targetStack对象的方法
  3. if (targetStack != null && isFocusedStack(targetStack)) {
  4. return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
  5. }
  6. //如果不在同一个ActivityStack中,则调用mFocusStack对象的方法
  7. if (r == null || r.state != RESUMED) {
  8. mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
  9. }
  10. return false;
  11. }
  1. ActivityStatck
  1. boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
  2. ...
  3. result = resumeTopActivityInnerLocked(prev, options);
  4. ...
  5. }
  6. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  7. ...
  8. if (mResumedActivity != null) {
  9. //同步等待pause当前Activity的结果,但在pause时,已经把mResumedActivity置为了null,所以不走这里
  10. pausing |= startPausingLocked(userLeaving, false, next, false);
  11. ...
  12. }
  13. ...
  14. return true;
  15. ...
  16. //开始启动下一个Activity
  17. mStackSupervisor.startSpecificActivityLocked(next, true, false);
  18. ...
  19. }
  1. ActivityStackSupervisor
  1. void startSpecificActivityLocked(ActivityRecord r,
  2. boolean andResume, boolean checkConfig) {
  3. if (app != null && app.thread != null) {
  4. ...
  5. realStartActivityLocked(r, app, andResume, checkConfig);
  6. return;
  7. }
  8. ...
  9. //启动跨进程的Activity需要先开启新的应用进程
  10. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
  11. "activity", r.intent.getComponent(), false, false, true);
  12. }
  13. final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
  14. boolean andResume, boolean checkConfig) throws RemoteException {
  15. ...
  16. app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
  17. System.identityHashCode(r), r.info,
  18. // TODO: Have this take the merged configuration instead of separate global
  19. // and override configs.
  20. mergedConfiguration.getGlobalConfiguration(),
  21. mergedConfiguration.getOverrideConfiguration(), r.compat,
  22. r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
  23. r.persistentState, results, newIntents, !andResume,
  24. mService.isNextTransitionForward(), profilerInfo);
  25. ...
  26. }
  1. ActivityThread$ApplicationThread
  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
  2. ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
  3. CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
  4. int procState, Bundle state, PersistableBundle persistentState,
  5. List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
  6. boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
  7. ...
  8. sendMessage(H.LAUNCH_ACTIVITY, r);
  9. }
  1. ActivityThread
  1. private void sendMessage(int what, Object obj) {
  2. sendMessage(what, obj, 0, 0, false);
  3. }
  4. private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
  5. ...
  6. mH.sendMessage(msg);
  7. }
  1. ActivityThread$H
  1. public void handleMessage(Message msg) {
  2. ...
  3. switch (msg.what) {
  4. case LAUNCH_ACTIVITY:
  5. {
  6. ....
  7. handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
  8. ....
  9. }
  10. break;
  11. ...
  12. }
  13. }
  1. ActivityThread
  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
  2. ...
  3. Activity a = performLaunchActivity(r, customIntent);
  4. }
  5. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent){
  6. ...
  7. if (r.isPersistable()) {
  8. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  9. } else {
  10. mInstrumentation.callActivityOnCreate(activity, r.state);
  11. }
  12. ...
  13. }
  1. Instumentation
  1. public void callActivityOnCreate(Activity activity, Bundle icicle) {
  2. prePerformCreate(activity);
  3. activity.performCreate(icicle);
  4. postPerformCreate(activity);
  5. }
  1. Activity
  1. final void performCreate(Bundle icicle) {
  2. performCreate(icicle, null);
  3. }
  4. final void performCreate(Bundle icicle, PersistableBundle persistentState) {
  5. ...
  6. if (persistentState != null) {
  7. onCreate(icicle, persistentState);
  8. } else {
  9. onCreate(icicle);
  10. }
  11. ...
  12. }
Activity启动流程

为了叙述方便,我们假设Activity A要启动Activity B。

  1. Activity A向AMS发送一个启动Activity B的进程间通信请求;
  2. AMS会将要启动的Activity B的组件信息保存下来,然后通过Binder通信(ApplicationThread及其接口定义语言),让Activity A执行pause操作;
  3. Activity B完成pause操作后,通过Binder通信(ActivityManagerService及其接口定义语言)通知AMS,可以执行启动Activity B的操作了(要启动的activity信息保存在了栈顶);
  4. 在启动之前,如果发现Activity B的应用程序进程不存在,会先启动一个新的进程(上述调用栈没涉及,同学们可自行查看源码);
  5. AMS执行一系列启动Activity B的操作,并通过Binder通信(ApplicationThread及其接口定义语言)进行跨进程调用,将Activity B启动起来;
关于AMS
  • AMS的启动是在SystemServer(系统进程)中启动的,同其他Android应用一样,也是由Zygote进程fork出来的:
  1. public final class SystemServer {
  2. /**
  3. * The main entry point from zygote.
  4. * 注释写的很清楚了,SystemServer进程是有Zygote进程fork出来的
  5. */
  6. public static void main(String[] args) {
  7. new SystemServer().run();
  8. }
  9. private void run() {
  10. ...
  11. startBootstrapServices();
  12. ...
  13. }
  14. private void startBootstrapServices() {
  15. ...
  16. // Activity manager runs the show.
  17. traceBeginAndSlog("StartActivityManager");
  18. //开启ActivityManagerService进程
  19. mActivityManagerService = mSystemServiceManager.startService(
  20. ActivityManagerService.Lifecycle.class).getService();
  21. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  22. mActivityManagerService.setInstaller(installer);
  23. traceEnd();
  24. ...
  25. }
  26. }
  • AMS与APP进程的通信:
  1. APP进程通过IActivityManager.aidl接口向AMS进程进行通信。
    ActivityManager.getService()获得AMS的Binder接口,再通过Stub.asInterface的方式,转成IActivityManager的接口,通过IActivityManager与AMS进行通信,实现RPC远程跨进程调用;
    Instrumentation
  1. int result = ActivityManager.getService()
  2. .startActivity(whoThread, who.getBasePackageName(), intent,
  3. intent.resolveTypeIfNeeded(who.getContentResolver()),
  4. token, target, requestCode, 0, null, options);

ActivityManager

  1. public static IActivityManager getService() {
  2. return IActivityManagerSingleton.get();
  3. }
  4. private static final Singleton<IActivityManager> IActivityManagerSingleton =
  5. new Singleton<IActivityManager>() {
  6. @Override
  7. protected IActivityManager create() {
  8. final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
  9. final IActivityManager am = IActivityManager.Stub.asInterface(b);
  10. return am;
  11. }
  12. };
  1. AMS进程通过IApplication.aidl接口向APP进程进行通信。
    在AMS内部持有每个ActivityThread的IApplicatinThread接口实例,用时可以直接调用。同IActivityManager,也是通过Binder进行进程间通信。

 

转载于:https://my.oschina.net/u/920274/blog/3060483

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/680258
推荐阅读
相关标签
  

闽ICP备14008679号