美文网首页
Activity启动流程

Activity启动流程

作者: 北疆小兵 | 来源:发表于2019-10-25 18:52 被阅读0次

Activity启动过程分析

一.概要

本文主要通过解读源码角度分析Activity启动过程

这里先借用一张网上的Activity启动流程图

点击Launch启动流程分析.png

二.启动流程

2.1 Activity.startActivity

public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

 public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}

starActivity虽然有多个重载方法,但是最终都会调到startActivityForResult

2.2 startActivityForResult

[Activity.java]


if (mParent == null) {
    //[见小节2.3]
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread(), mToken, this,
            intent, requestCode, options);
    if (ar != null) {
        mMainThread.sendActivityResult(
            mToken, mEmbeddedID, requestCode, ar.getResultCode(),
            ar.getResultData());
    }
    //此时requestCode =-1
    if (requestCode >= 0) {
        mStartedActivity = true;
    }
    cancelInputsAndStartExitTransition(options);
} else {
    ...
}

startActivityForResult中调用的是Instrumentation的.execStartActivity() ,这里几个参数的作用如下:

  • context:当前activity的上下文
  • mMainThread.getApplicationThread:ApplicationThread对象,通过mMainThread.getApplicationThread()方法获取。
  • token:Binder对象,指向服务端一个ActivityRecord对象
  • target:待启动的Activity
  • requestCode:请求码,如果希望得到返回结果,传大于0的数字
  • options:Bundle对象

2.3 execStartActivity

[-> Instrumentation.java]

 IApplicationThread whoThread = (IApplicationThread) contextThread;
    ...

    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                if (am.match(who, null, intent)) {
                    am.mHits++;
                    //当该monitor阻塞activity启动,则直接返回
                    if (am.isBlocking()) {
                        return requestCode >= 0 ? am.getResult() : null;
                    }
                    break;
                }
            }
        }
    }
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess();
        //[见小节2.4]
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        //检查activity是否启动成功
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;

这个方法里面实际调用的是ActivityManagerNative.getDefault().startActivity,而ActivityManagerNative.getDefault()实际得到的是ActivityManangerProxy,这个对象是服务端系统进程AMS在客户端的代理, 这里就是通过Binder IPC 进入ActivityManangerNative,程序进入了system_server进行

2.5 AMS.startActivity

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());
}

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);
    //[见小节2.7]
    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
            resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
            profilerInfo, null, null, options, false, userId, null, null);
}

这里内部调用的是ActivityStarter对象的startActivityMayWait()

2.7 ActivityStart.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) {
    ...
    boolean componentSpecified = intent.getComponent() != null;
    //创建新的Intent对象,即便intent被修改也不受影响
    intent = new Intent(intent);

    //收集Intent所指向的Activity信息, 当存在多个可供选择的Activity,则直接向用户弹出resolveActivity [见2.7.1]
    ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);

    ActivityContainer container = (ActivityContainer)iContainer;
    synchronized (mService) {
        if (container != null && container.mParentActivity != null &&
                container.mParentActivity.state != RESUMED) {
            ... //不进入该分支, container == nul
        }

        final int realCallingPid = Binder.getCallingPid();
        final int realCallingUid = Binder.getCallingUid();
        int callingPid;
        if (callingUid >= 0) {
            callingPid = -1;
        } else if (caller == null) {
            callingPid = realCallingPid;
            callingUid = realCallingUid;
        } else {
            callingPid = callingUid = -1;
        }

        final ActivityStack stack;
        if (container == null || container.mStack.isOnHomeDisplay()) {
            stack = mFocusedStack; // 进入该分支
        } else {
            stack = container.mStack;
        }

        //此时mConfigWillChange = false
        stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0;

        final long origId = Binder.clearCallingIdentity();

        if (aInfo != null &&
                (aInfo.applicationInfo.privateFlags
                        &ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) {
            // heavy-weight进程处理流程, 一般情况下不进入该分支
            if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
                ...
            }
        }

        //[见流程2.8]
        int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                voiceSession, voiceInteractor, resultTo, resultWho,
                requestCode, callingPid, callingUid, callingPackage,
                realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
                componentSpecified, null, container, inTask);

        Binder.restoreCallingIdentity(origId);

        if (stack.mConfigWillChange) {
            ... //不进入该分支
        }

        if (outResult != null) {
            ... //不进入该分支
        }

        return res;
    }
}

这个方法先调用

  • ActivityInfo aInfo = ActivityStackSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo)
    获取ActivityInfo,然后调用ActivityStart.startActivityLocked()[见流程2.8], 我们先看ActivityStackSupervisor.resolveActivityn内部实现

2.8 Ass.startActivityLocked


# ActivityStart
 int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, TaskRecord inTask, String reason) {

       //获取调用者的进程记录对象
    ProcessRecord callerApp = null;
    if (caller != null) {
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }

    final int userId = aInfo != null ?  UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;

    ActivityRecord sourceRecord = null;
    ActivityRecord resultRecord = null;
    if (resultTo != null) {
        //获取调用者所在的Activity
        sourceRecord = isInAnyStackLocked(resultTo);
        if (sourceRecord != null) {
            if (requestCode >= 0 && !sourceRecord.finishing) {
                ... //requestCode = -1 则不进入
            }
        }
    }

    final int launchFlags = intent.getFlags();

    if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
        ... // activity执行结果的返回由源Activity转换到新Activity, 不需要返回结果则不会进入该分支
    }

    if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
        //从Intent中无法找到相应的Component
        err = ActivityManager.START_INTENT_NOT_RESOLVED;
    }

    if (err == ActivityManager.START_SUCCESS && aInfo == null) {
        //从Intent中无法找到相应的ActivityInfo
        err = ActivityManager.START_INTENT_NOT_RESOLVED;
    }

    if (err == ActivityManager.START_SUCCESS
            && !isCurrentProfileLocked(userId)
            && (aInfo.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
        //尝试启动一个后台Activity, 但该Activity对当前用户不可见
        err = ActivityManager.START_NOT_CURRENT_USER_ACTIVITY;
    }
    ...

    //执行后resultStack = null
    final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;

    ... //权限检查

    // ActivityController不为空的情况,比如monkey测试过程
    if (mService.mController != null) {
        Intent watchIntent = intent.cloneFilter();
        abort |= !mService.mController.activityStarting(watchIntent,
                aInfo.applicationInfo.packageName);
    }

    if (abort) {
        ... //权限检查不满足,才进入该分支则直接返回;
        return ActivityManager.START_SUCCESS;
    }

    // 创建Activity记录对象
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
            intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
            requestCode, componentSpecified, voiceSession != null, this, container, options);
    if (outActivity != null) {
        outActivity[0] = r;
    }

    if (r.appTimeTracker == null && sourceRecord != null) {
        r.appTimeTracker = sourceRecord.appTimeTracker;
    }
    // 将mFocusedStack赋予当前stack
    final ActivityStack stack = mFocusedStack;

    if (voiceSession == null && (stack.mResumedActivity == null
            || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
        // 前台stack还没有resume状态的Activity时, 则检查app切换是否允许 [见流程2.8.1]
        if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
                realCallingPid, realCallingUid, "Activity start")) {
            PendingActivityLaunch pal =
                    new PendingActivityLaunch(r, sourceRecord, startFlags, stack);
            // 当不允许切换,则把要启动的Activity添加到mPendingActivityLaunches对象, 并且直接返回.
            mPendingActivityLaunches.add(pal);
            ActivityOptions.abort(options);
            return ActivityManager.START_SWITCHES_CANCELED;
        }
    }

    if (mService.mDidAppSwitch) {
        //从上次禁止app切换以来,这是第二次允许app切换,因此将允许切换时间设置为0,则表示可以任意切换app
        mService.mAppSwitchesAllowedTime = 0;
    } else {
        mService.mDidAppSwitch = true;
    }

    //处理 pendind Activity的启动, 这些Activity是由于app switch禁用从而被hold的等待启动activity [见流程2.8.2]
    doPendingActivityLaunchesLocked(false);

    //[见流程2.9]
    err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
            startFlags, true, options, inTask);

    if (err < 0) {
        notifyActivityDrawnForKeyguard();
    }
    return err;
    }
    

startActivityLocked内部调用的是ActivityStart.startActivity

2.8.1 AMS.AMS.checkAppSwitchAllowedLocked

boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, int callingPid, int callingUid, String name) {
    if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
        return true;
    }

    int perm = checkComponentPermission(
            android.Manifest.permission.STOP_APP_SWITCHES, sourcePid,
            sourceUid, -1, true);
    if (perm == PackageManager.PERMISSION_GRANTED) {
        return true;
    }

    if (callingUid != -1 && callingUid != sourceUid) {
        perm = checkComponentPermission(
                android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
                callingUid, -1, true);
        if (perm == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
    }

    return false;
}

2.9 ASS.startActivityUncheckedLocked

2.10 ASS.startActivityLocked

2.11 ASS.resumeTopActivitiesLocked

2.12 AS.resumeTopActivityLocked

2.13 AS.resumeTopActivityInnerLocked

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
    ... //系统没有进入booting或booted状态,则不允许启动Activity

    ActivityRecord parent = mActivityContainer.mParentActivity;
    if ((parent != null && parent.state != ActivityState.RESUMED) ||
            !mActivityContainer.isAttachedLocked()) {
        return false;
    }
    //top running之后的任意处于初始化状态且有显示StartingWindow, 则移除StartingWindow
    cancelInitializingActivities();

    //找到第一个没有finishing的栈顶activity
    final ActivityRecord next = topRunningActivityLocked(null);

    final boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;

    final TaskRecord prevTask = prev != null ? prev.task : null;
    if (next == null) {
        final String reason = "noMoreActivities";
        if (!mFullscreen) {
            //当该栈没有全屏,则尝试聚焦到下一个可见的stack
            final ActivityStack stack = getNextVisibleStackLocked();
            if (adjustFocusToNextVisibleStackLocked(stack, reason)) {
                return mStackSupervisor.resumeTopActivitiesLocked(stack, prev, null);
            }
        }
        ActivityOptions.abort(options);
        final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
        //启动home桌面activity
        return isOnHomeDisplay() &&
                mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
    }

    next.delayedResume = false;

    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        return false;
    }

    final TaskRecord nextTask = next.task;
    if (prevTask != null && prevTask.stack == this &&
            prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
        if (prevTask == nextTask) {
            prevTask.setFrontOfTask();
        } else if (prevTask != topTask()) {
            final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
            mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
        } else if (!isOnHomeDisplay()) {
            return false;
        } else if (!isHomeStack()){
            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                    HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
        }
    }

    //处于睡眠或者关机状态,top activity已暂停的情况下
    if (mService.isSleepingOrShuttingDown()
            && mLastPausedActivity == next
            && mStackSupervisor.allPausedActivitiesComplete()) {
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        return false;
    }

    if (mService.mStartedUsers.get(next.userId) == null) {
        return false; //拥有该activity的用户没有启动则直接返回
    }

    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mWaitingVisibleActivities.remove(next);

    mActivityTrigger.activityResumeTrigger(next.intent, next.info, next.appInfo);

    if (!mStackSupervisor.allPausedActivitiesComplete()) {
        return false; //当正处于暂停activity,则直接返回
    }

    mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);

    //需要等待暂停当前activity完成,再resume top activity
    boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    //暂停其他Activity[见小节2.13.1]
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
    if (mResumedActivity != null) {
        //当前resumd状态activity不为空,则需要先暂停该Activity
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
    }
    if (pausing) {
        if (next.app != null && next.app.thread != null) {
            mService.updateLruProcessLocked(next.app, true, null);
        }
        return true;
    }

    if (mService.isSleeping() && mLastNoHistoryActivity != null &&
            !mLastNoHistoryActivity.finishing) {
        requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                null, "resume-no-history", false);
        mLastNoHistoryActivity = null;
    }

    if (prev != null && prev != next) {
        if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                && next != null && !next.nowVisible) {
            mStackSupervisor.mWaitingVisibleActivities.add(prev);
        } else {
            if (prev.finishing) {
                mWindowManager.setAppVisibility(prev.appToken, false);
            }
        }
    }

    AppGlobals.getPackageManager().setPackageStoppedState(
            next.packageName, false, next.userId);

    boolean anim = true;
    if (mIsAnimationBoostEnabled == true && mPerf == null) {
        mPerf = new BoostFramework();
    }
    if (prev != null) {
        if (prev.finishing) {
            if (mNoAnimActivities.contains(prev)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_CLOSE
                        : AppTransition.TRANSIT_TASK_CLOSE, false);
                if(prev.task != next.task && mPerf != null) {
                   mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal);
                }
            }
            mWindowManager.setAppWillBeHidden(prev.appToken);
            mWindowManager.setAppVisibility(prev.appToken, false);
        } else {
            if (mNoAnimActivities.contains(next)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_OPEN
                        : next.mLaunchTaskBehind
                                ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
                                : AppTransition.TRANSIT_TASK_OPEN, false);
                if(prev.task != next.task && mPerf != null) {
                    mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal);
                }
            }
        }
    } else {
        if (mNoAnimActivities.contains(next)) {
            anim = false;
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
        } else {
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false);
        }
    }

    Bundle resumeAnimOptions = null;
    if (anim) {
        ActivityOptions opts = next.getOptionsForTargetActivityLocked();
        if (opts != null) {
            resumeAnimOptions = opts.toBundle();
        }
        next.applyOptionsLocked();
    } else {
        next.clearOptionsLocked();
    }

    ActivityStack lastStack = mStackSupervisor.getLastStack();
    //进程已存在的情况
    if (next.app != null && next.app.thread != null) {
        //activity正在成为可见
        mWindowManager.setAppVisibility(next.appToken, true);

        next.startLaunchTickingLocked();

        ActivityRecord lastResumedActivity = lastStack == null ? null :lastStack.mResumedActivity;
        ActivityState lastState = next.state;

        mService.updateCpuStats();
        //设置Activity状态为resumed
        next.state = ActivityState.RESUMED;
        mResumedActivity = next;
        next.task.touchActiveTime();
        mRecentTasks.addLocked(next.task);
        mService.updateLruProcessLocked(next.app, true, null);
        updateLRUListLocked(next);
        mService.updateOomAdjLocked();

        boolean notUpdated = true;
        if (mStackSupervisor.isFrontStack(this)) {
            Configuration config = mWindowManager.updateOrientationFromAppTokens(
                    mService.mConfiguration,
                    next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
            if (config != null) {
                next.frozenBeforeDestroy = true;
            }
            notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
        }

        if (notUpdated) {
            ActivityRecord nextNext = topRunningActivityLocked(null);

            if (nextNext != next) {
                mStackSupervisor.scheduleResumeTopActivities();
            }
            if (mStackSupervisor.reportResumedActivityLocked(next)) {
                mNoAnimActivities.clear();
                return true;
            }
            return false;
        }

        try {
            //分发所有pending结果.
            ArrayList<ResultInfo> a = next.results;
            if (a != null) {
                final int N = a.size();
                if (!next.finishing && N > 0) {
                    next.app.thread.scheduleSendResult(next.appToken, a);
                }
            }

            if (next.newIntents != null) {
                next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
            }

            next.sleeping = false;
            mService.showAskCompatModeDialogLocked(next);
            next.app.pendingUiClean = true;
            next.app.forceProcessStateUpTo(mService.mTopProcessState);
            next.clearOptionsLocked();
            //触发onResume()
            next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                    mService.isNextTransitionForward(), resumeAnimOptions);

            mStackSupervisor.checkReadyForSleepLocked();

        } catch (Exception e) {
            ...
            return true;
        }
        next.visible = true;
        completeResumeLocked(next);
        next.stopped = false;

    } else {
        if (!next.hasBeenLaunched) {
            next.hasBeenLaunched = true;
        } else {
            if (SHOW_APP_STARTING_PREVIEW) {
                mWindowManager.setAppStartingWindow(
                        next.appToken, next.packageName, next.theme,
                        mService.compatibilityInfoForPackageLocked(
                                next.info.applicationInfo),
                        next.nonLocalizedLabel,
                        next.labelRes, next.icon, next.logo, next.windowFlags,
                        null, true);
            }
        }
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}

2.13.1

final boolean startPausingLocked(boolean userLeavin){
    if (mPausingActivity != null) {
      if (!mService.isSleeping()) {
          completePauseLocked(false);
      }
  }
  ActivityRecord prev = mResumedActivity;
  ...

  if (mActivityContainer.mParentActivity == null) {
      //暂停所有子栈的Activity
      mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
  }
  ...
  final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();

  if (prev.app != null && prev.app.thread != null) {
      EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
              prev.userId, System.identityHashCode(prev),
              prev.shortComponentName);
      mService.updateUsageStats(prev, false);
      //暂停目标Activity
      prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
              userLeaving, prev.configChangeFlags, dontWait);
  }else {
      ...
  }

  if (!uiSleeping && !mService.isSleepingOrShuttingDown()) {
      mStackSupervisor.acquireLaunchWakelock(); //申请wakelock
  }

  if (mPausingActivity != null) {
      if (!uiSleeping) {
          prev.pauseKeyDispatchingLocked();
      }

      if (dontWait) {
          completePauseLocked(false);
          return false;
      } else {
          Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
          msg.obj = prev;
          prev.pauseTime = SystemClock.uptimeMillis();
          //500ms后,执行暂停超时的消息
          mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
          return true;
      }

  } else {
      if (!resuming) { //调度暂停失败,则认为已暂停完成,开始执行resume操作
          mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null);
      }
      return false;
  }

}

通过Binder调用,进入Activity
suo在进程来执行schedulePauseActivity, prev.app.thread.schedulePauseActivity暂停当前activtiy,再执行completePauseLocked

2.14 ASS.startSpecificActivityLocked


void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);

    r.task.stack.setLaunchTime(r);

    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                    || !"android".equals(r.info.packageName)) {
                app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                        mService.mProcessStats);
            }
            //真正的启动Activity【见流程2.17】
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }

    }
    //当进程不存在则创建进程【见流程2.15】
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

调用realStartActivityLocked启动目标activity

2.16


//【见流程2.17】
  //将该进程设置为前台进程PROCESS_STATE_TOP
        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);

通过binder通信调用app进程的ApplicationThreadProxy.scheduleLaunchActivity

2.17

private class ApplicationThread extends IApplicationThread.Stub {
     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);

}

通过mH发送LAUNCH_ACTIVITY启动activity消息

2.17. handleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    //最终回调目标Activity的onConfigurationChanged()
    handleConfigurationChanged(null, null);
    //初始化wms
    WindowManagerGlobal.initialize();
    //最终回调目标Activity的onCreate[见流程2.23]
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        Bundle oldState = r.state;
        //最终回调目标Activity的onStart,onResume.
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed);

        if (!r.activity.mFinished && r.startsNotResumed) {
            r.activity.mCalled = false;
            mInstrumentation.callActivityOnPause(r.activity);
            r.paused = true;
        }
    } else {
        //存在error则停止该Activity
        ActivityManagerNative.getDefault()
            .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
    }
}

2.18 ActityThread.performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }

    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName,
                r.activityInfo.targetActivity);
    }

    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        ...
    }

    try {
        //创建Application对象
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            Context appContext = createBaseContextForActivity(r, activity);
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);

            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor);

            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            activity.mStartedActivity = false;
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
            r.activity = activity;
            r.stopped = true;
            if (!r.activity.mFinished) {
                activity.performStart();
                r.stopped = false;
            }
            if (!r.activity.mFinished) {
                if (r.isPersistable()) {
                    if (r.state != null || r.persistentState != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                r.persistentState);
                    }
                } else if (r.state != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                }
            }
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state,
                            r.persistentState);
                } else {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state);
                }
                ...
            }
        }
        r.paused = true;

        mActivities.put(r.token, r);

    }  catch (Exception e) {
        ...
    }

    return activity;
}


首先通过Instrumentation.newActivity对象实例化了Activity对象, 然后调用r.packageInfo.makeApplication实例化了Application对象, 然后回调Activity的onCreate()、onStart()、onResume,至此activity的启动流程就结束了

总结

从另一个角度用下图来概括activity启动过程

启动流程.jpeg

启动流程:

点击桌面App图标,Launcher进程采用Binder IPC向system_server进程发起startActivity请求;
system_server进程接收到请求后,向zygote进程发送创建进程的请求;
Zygote进程fork出新的子进程,即App进程;
App进程,通过Binder IPC向sytem_server进程发起attachApplication请求;
system_server进程在收到请求后,进行一系列准备工作后,再通过binder IPC向App进程发送scheduleLaunchActivity请求;
App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息;
主线程在收到Message后,通过发射机制创建目标Activity,并回调Activity.onCreate()等方法。

相关文章

网友评论

      本文标题:Activity启动流程

      本文链接:https://www.haomeiwen.com/subject/xydevctx.html