Android Activity启动流程分析

发表于:2018-4-17 11:56

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:hailwind    来源:CSDN

分享:

  ActivityManagerService启动Activity主要会涉及到以下的一些方法。
  ActivityManagerService.startActivity() 
  ActvityiManagerService.startActivityAsUser() 
  ActivityStackSupervisor.startActivityMayWait() 
  ActivityStackSupervisor.startActivityLocked() 
  ActivityStackSupervisor.startActivityUncheckedLocked() 
  ActivityStackSupervisor.startActivityLocked() 
  ActivityStackSupervisor.resumeTopActivitiesLocked() 
  ActivityStackSupervisor.resumeTopActivityInnerLocked() 
  当ActivityManagerService调用startActivity方法后,该方法调用的是startActivityAsUser(),该方法的源码如下:
  @Override  
  public final int startActivityAsUser(IApplicationThread caller, String callingPackage,  
          Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,  
          int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {  
      enforceNotIsolatedCaller("startActivity");  
      userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),  
              userId, false, ALLOW_FULL_ONLY, "startActivity", null);  
      // TODO: Switch to user app stacks here.  
      return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,  
              resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,  
              profilerInfo, null, null, bOptions, false, userId, null, null,  
              "startActivityAsUser");  
  }
  
  可以看到这里只是进行了一些关于userid的逻辑判断,然后就调用mStackSupervisor.startActivityMayWait方法,该方法涉及的源码比较多,下面截取一些核心的代码实现:
  final int startActivityMayWait(IApplicationThread caller, int callingUid,
              String callingPackage, Intent intent, String resolvedType,
              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
              IBinder resultTo, String resultWho, int requestCode, int startFlags,
              ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
              Bundle options, boolean ignoreTargetSecurity, int userId,
              IActivityContainer iContainer, TaskRecord inTask) {
              ...
              int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                      voiceSession, voiceInteractor, resultTo, resultWho,
                      requestCode, callingPid, callingUid, callingPackage,
                      realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
                      componentSpecified, null, container, inTask);
              ...
              return res;
      }
  该方法在启动Activity后执行了一些逻辑判断后,最终调用startActivityLocked方法。
  final int startActivityLocked(IApplicationThread caller,
              Intent intent, String resolvedType, ActivityInfo aInfo,
              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
              IBinder resultTo, String resultWho, int requestCode,
              int callingPid, int callingUid, String callingPackage,
              int realCallingPid, int realCallingUid, int startFlags, Bundle options,
              boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
              ActivityContainer container, TaskRecord inTask) {
          int err = ActivityManager.START_SUCCESS;
          ...
          err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
                  startFlags, true, options, inTask);
          ...
          return err;
      }
  这个方法中主要构造了ActivityManagerService端的Activity对象–>ActivityRecord,并在执行了一些逻辑判断后调用了startActivityUncheckedLocked方法。
  final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord,
              IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
              boolean doResume, Bundle options, TaskRecord inTask) {
          ...
          ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
          targetStack.mLastPausedActivity = null;
          targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
          if (!launchTaskBehind) {
              // Don't set focus on an activity that's going to the back.
              mService.setFocusedActivityLocked(r, "startedActivity");
          }
          return ActivityManager.START_SUCCESS;
      }

  startActivityUncheckedLocked方法中只要执行了不同启动模式不同栈的处理,并最后调用了startActivityLocked的重载方法。
  final void startActivityLocked(ActivityRecord r, boolean newTask,
              boolean doResume, boolean keepCurTransition, Bundle options) {
          ...
          if (doResume) {
              mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
          }
      }
  而这个startActivityLocked方法主要执行初始化了windowManager服务,然后调用resumeTopActivitiesLocked方法。
  boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
              Bundle targetOptions) {
          if (targetStack == null) {
              targetStack = mFocusedStack;
          }
          // Do targetStack first.
          boolean result = false;
          if (isFrontStack(targetStack)) {
              result = targetStack.resumeTopActivityLocked(target, targetOptions);
          }
          for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
              final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
              for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                  final ActivityStack stack = stacks.get(stackNdx);
                  if (stack == targetStack) {
                      // Already started above.
                      continue;
                  }
                  if (isFrontStack(stack)) {
                      stack.resumeTopActivityLocked(null);
                  }
              }
          }
          return result;
      }
  该函数最终又调用了resumeTopActivityLocked方法,
  final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
          if (mStackSupervisor.inResumeTopActivity) {
              // Don't even start recursing.
              return false;
          }
          boolean result = false;
          try {
              // Protect against recursion.
              mStackSupervisor.inResumeTopActivity = true;
              if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
                  mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
                  mService.updateSleepIfNeededLocked();
              }
              result = resumeTopActivityInnerLocked(prev, options);
          } finally {
              mStackSupervisor.inResumeTopActivity = false;
          }
          return result;
      }
  ApplicationThread
  前面说过,ApplicationThread是ActivityThread的内部类,因此ApplicationThread可以调用外部类ActivityThread的方法,启动Activity的操作交给了ActivityThread来处理。那么首先来看一下ApplicationThread$scheduleLaunchActivity的源码实现。
  @Override  
         public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,  
                 ActivityInfo info, Configuration curConfig, Configuration overrideConfig,  
                 CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,  
                 int procState, Bundle state, PersistableBundle persistentState,  
                 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,  
                 boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {  
             updateProcessState(procState, false);  
             ActivityClientRecord r = new ActivityClientRecord();  
             r.token = token;  
             r.ident = ident;  
             r.intent = intent;  
             r.referrer = referrer;  
             r.voiceInteractor = voiceInteractor;  
             r.activityInfo = info;  
             r.compatInfo = compatInfo;  
             r.state = state;  
             r.persistentState = persistentState;  
             r.pendingResults = pendingResults;  
             r.pendingIntents = pendingNewIntents;  
             r.startsNotResumed = notResumed;  
             r.isForward = isForward;  
             r.profilerInfo = profilerInfo;  
             r.overrideConfig = overrideConfig;  
             updatePendingConfiguration(curConfig);  
             sendMessage(H.LAUNCH_ACTIVITY, r);  
         }  
  上面代码最终调用了ActivityThread$sendMessage函数,该部分代码如下:
  private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {  
          if (DEBUG_MESSAGES) Slog.v(  
              TAG, "SCHEDULE " + what + " " + mH.codeToString(what)  
              + ": " + arg1 + " / " + obj);  
          Message msg = Message.obtain();  
          msg.what = what;  
          msg.obj = obj;  
          msg.arg1 = arg1;  
          msg.arg2 = arg2;  
          if (async) {  
              msg.setAsynchronous(true);  
          }  
          mH.sendMessage(msg);  
  } 
  上面使用了Handler机制,来看一下H$handleMessage源码。
  private class H extends Handler {  
      //...code  
      public void handleMessage(Message msg) {  
              if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));  
              switch (msg.what) {  
                  case LAUNCH_ACTIVITY: {  
                      Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");  
                      final ActivityClientRecord r = (ActivityClientRecord) msg.obj;  
                      r.packageInfo = getPackageInfoNoCheck(  
                              r.activityInfo.applicationInfo, r.compatInfo);  
                      handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");  
                      Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);  
                  } break;  
      //...code  
  } 

  当接受到消息后,最终调用ActivityThread$handleLaunchActivity方法启动Activity。
 
  private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {  
      //...  
      Activity a = performLaunchActivity(r, customIntent);  
      //...  
      if (a != null) {  
          //...  
          handleResumeActivity(r.token, false, r.isForward,  
                      !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);  
          //...  
      } else {  
          // If there was an error, for any reason, tell the activity manager to stop us.  
          try {  
               ActivityManager.getService()  
                      .finishActivity(r.token, Activity.RESULT_CANCELED, null,  
                              Activity.DONT_FINISH_TASK_WITH_ACTIVITY);  
              } catch (RemoteException ex) {  
                  throw ex.rethrowFromSystemServer();  
              }  
      }  
  } 
  也就是performLaunchActivity,到此我相信大部分的同学都可以看得懂了。
22/2<12
100家互联网大公司java笔试题汇总,填问卷领取~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2023
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号