android activity堆栈创建与查找

stack与task抽象模型

activity在service端时 activityRecord 他被task管理,task又被stack管理
内存中是以如下抽象的方式存储,方便框架创建查找管理等等之类的功能.


堆栈.png

看一下dumpsys中看到的真实情况,一般情况下launcher占用了stack #0,
adb shell dumpsys activity activities
字段说明:
type=standard 这个不用说明,最常见的
type=home 很显然,这个是launcher
mode = fullscreen 这个是说当前activity是全屏的,如果了解 分屏 与 freeform, pip 那么对应的值也不同
比如:
mode=split-screen-secondary 分屏
mode=freeform 自由窗口
mode=pinned pip视频画中画

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)
Display #0 (activities from top to bottom):

  Stack #506: type=standard mode=fullscreen
  isSleeping=false
  mBounds=Rect(0, 0 - 0, 0)
    Task id #498
    mBounds=Rect(0, 0 - 0, 0)
    mMinWidth=-1
    mMinHeight=-1
    mLastNonFullscreenBounds=null
    * TaskRecord{ac6fa42 #498 A=com.douban.frodo U=0 StackId=506 sz=2}
      userId=0 effectiveUid=u0a193 mCallingUid=u0a193 mUserSetupComplete=true mCallingPackage=com.douban.frodo
      affinity=com.douban.frodo
      intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.douban.frodo/.activity.SplashActivity}
      mActivityComponent=com.douban.frodo/.activity.SplashActivity
      autoRemoveRecents=false isPersistable=true numFullscreen=2 activityType=1
      rootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE
      Activities=[ActivityRecord{98eb699 u0 com.douban.frodo/.MainActivity t498}, ActivityRecord{8491c91 u0 com.douban.frodo/.group.activity.GroupTopicActivity t498}]
      askedCompatMode=false inRecents=true isAvailable=true
      mRootProcess=ProcessRecord{9b4fda2 2961:com.douban.frodo/u0a193}
      stackId=506
      hasBeenVisible=true mResizeMode=RESIZE_MODE_RESIZEABLE mSupportsPictureInPicture=false isResizeable=true lastActiveTime=588689289 (inactive for 13s)
      * Hist #1: ActivityRecord{8491c91 u0 com.douban.frodo/.group.activity.GroupTopicActivity t498}
          packageName=com.douban.frodo processName=com.douban.frodo
          launchedFromUid=10193 launchedFromPackage=com.douban.frodo userId=0
          app=ProcessRecord{9b4fda2 2961:com.douban.frodo/u0a193}
          Intent { cmp=com.douban.frodo/.group.activity.GroupTopicActivity (has extras) }
          frontOfTask=false task=TaskRecord{ac6fa42 #498 A=com.douban.frodo U=0 StackId=506 sz=2}
          taskAffinity=com.douban.frodo
          mActivityComponent=com.douban.frodo/.group.activity.GroupTopicActivity
          baseDir=/data/app/com.douban.frodo-Fi3_ei5LS2d4dA3_S35NSQ==/base.apk
          dataDir=/data/user/0/com.douban.frodo
          stateNotNeeded=false componentSpecified=true mActivityType=standard
          compat={480dpi} labelRes=0x0 icon=0x7f0e0000 theme=0x7f11025b
          mLastReportedConfigurations:
           mGlobalConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.21225 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
           mOverrideConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          CurrentConfiguration={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          taskDescription: label="null" icon=null iconResource=0 iconFilename=null primaryColor=ff42bd56
           backgroundColor=fffafafa
           statusBarColor=ffffffff
           navigationBarColor=ffffffff
          launchFailed=false launchCount=0 lastLaunchTime=-5m36s719ms
          haveState=false icicle=null
          state=RESUMED stopped=false delayedResume=false finishing=false
          keysPaused=false inHistory=true visible=true sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_REMOVED
          fullscreen=true noDisplay=false immersive=false launchMode=0
          frozenBeforeDestroy=false forceNewConfig=false
          mActivityType=standard
           nowVisible=true lastVisibleTime=-13s441ms
          resizeMode=RESIZE_MODE_RESIZEABLE
          mLastReportedMultiWindowMode=false mLastReportedPictureInPictureMode=false
      * Hist #0: ActivityRecord{98eb699 u0 com.douban.frodo/.MainActivity t498}
          packageName=com.douban.frodo processName=com.douban.frodo
          launchedFromUid=10193 launchedFromPackage=com.douban.frodo userId=0
          app=ProcessRecord{9b4fda2 2961:com.douban.frodo/u0a193}
          Intent { flg=0x10000000 cmp=com.douban.frodo/.MainActivity }
          frontOfTask=true task=TaskRecord{ac6fa42 #498 A=com.douban.frodo U=0 StackId=506 sz=2}
          taskAffinity=com.douban.frodo
          mActivityComponent=com.douban.frodo/.MainActivity
          baseDir=/data/app/com.douban.frodo-Fi3_ei5LS2d4dA3_S35NSQ==/base.apk
          dataDir=/data/user/0/com.douban.frodo
          stateNotNeeded=false componentSpecified=true mActivityType=standard
          compat={480dpi} labelRes=0x7f1000e4 icon=0x7f0e0000 theme=0x7f11025c
          mLastReportedConfigurations:
           mGlobalConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.21225 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
           mOverrideConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.2 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          CurrentConfiguration={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.2 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          taskDescription: label="null" icon=null iconResource=0 iconFilename=null primaryColor=ff42bd56
           backgroundColor=fffafafa
           statusBarColor=ffffffff
           navigationBarColor=ffffffff
          launchFailed=false launchCount=0 lastLaunchTime=-6m44s526ms
          haveState=true icicle=Bundle[mParcelledData.dataSize=25092]
          state=STOPPED stopped=true delayedResume=false finishing=false
          keysPaused=false inHistory=true visible=false sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_NOT_SHOWN
          fullscreen=true noDisplay=false immersive=false launchMode=2
          frozenBeforeDestroy=false forceNewConfig=false
          mActivityType=standard
           nowVisible=false lastVisibleTime=-5m41s249ms
          resizeMode=RESIZE_MODE_RESIZEABLE
          mLastReportedMultiWindowMode=false mLastReportedPictureInPictureMode=false

    Running activities (most recent first):
      TaskRecord{ac6fa42 #498 A=com.douban.frodo U=0 StackId=506 sz=2}
        Run #1: ActivityRecord{8491c91 u0 com.douban.frodo/.group.activity.GroupTopicActivity t498}
        Run #0: ActivityRecord{98eb699 u0 com.douban.frodo/.MainActivity t498}

    mResumedActivity: ActivityRecord{8491c91 u0 com.douban.frodo/.group.activity.GroupTopicActivity t498}
    mLastPausedActivity: ActivityRecord{4b6e7cf u0 com.douban.frodo/.activity.SplashActivity t-1 f}

  Stack #0: type=home mode=fullscreen
  isSleeping=false
  mBounds=Rect(0, 0 - 0, 0)

    Task id #5
    mBounds=Rect(0, 0 - 0, 0)
    mMinWidth=-1
    mMinHeight=-1
    mLastNonFullscreenBounds=null
    * TaskRecord{3859883 #5 A=cn.nubia.launcher U=0 StackId=0 sz=1}
      userId=0 effectiveUid=u0a82 mCallingUid=u0a226 mUserSetupComplete=true mCallingPackage=com.tencent.mm
      affinity=cn.nubia.launcher
      intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=cn.nubia.launcher/com.android.launcher3.Launcher}
      mActivityComponent=cn.nubia.launcher/com.android.launcher3.Launcher
      autoRemoveRecents=false isPersistable=true numFullscreen=1 activityType=2
      rootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE
      Activities=[ActivityRecord{a912b91 u0 cn.nubia.launcher/com.android.launcher3.Launcher t5}]
      askedCompatMode=false inRecents=true isAvailable=true
      mRootProcess=ProcessRecord{214e5fd 4555:cn.nubia.launcher/u0a82}
      stackId=0
      hasBeenVisible=true mResizeMode=RESIZE_MODE_RESIZEABLE mSupportsPictureInPicture=false isResizeable=true lastActiveTime=586297911 (inactive for 2405s)
      * Hist #0: ActivityRecord{a912b91 u0 cn.nubia.launcher/com.android.launcher3.Launcher t5}
          packageName=cn.nubia.launcher processName=cn.nubia.launcher
          launchedFromUid=1000 launchedFromPackage=cn.nubia.setupwizard userId=0
          app=ProcessRecord{214e5fd 4555:cn.nubia.launcher/u0a82}
          Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=cn.nubia.launcher/com.android.launcher3.Launcher }
          frontOfTask=true task=TaskRecord{3859883 #5 A=cn.nubia.launcher U=0 StackId=0 sz=1}
          taskAffinity=cn.nubia.launcher
          mActivityComponent=cn.nubia.launcher/com.android.launcher3.Launcher
          baseDir=/system/app/nubia_Launcher/nubia_Launcher.apk
          dataDir=/data/user_de/0/cn.nubia.launcher
          stateNotNeeded=true componentSpecified=true mActivityType=home
          compat={480dpi} labelRes=0x7f0a0011 icon=0x7f030003 theme=0x7f1000f1
          mLastReportedConfigurations:
           mGlobalConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.21225 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
           mOverrideConfig={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=home mAlwaysOnTop=undefined mRotation=ROTATION_0} s.436 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          CurrentConfiguration={1.0 460mcc1mnc [zh_CN] ldltr sw360dp w360dp h743dp 480dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 0 - 1080, 2340) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=home mAlwaysOnTop=undefined mRotation=ROTATION_0} s.436 themeChanged=1 themeChangedFlags=268451851 typefaceTimeStamp=1587924437837}
          RequestedOverrideConfiguration={0.0 ?mcc?mnc ?localeList ?layoutDir ?swdp ?wdp ?hdp ?density ?lsize ?long ?ldr ?wideColorGamut ?orien ?uimode ?night ?touch ?keyb/?/? ?nav/? winConfig={ mBounds=Rect(0, 0 - 0, 0) mAppBounds=null mWindowingMode=undefined mDisplayWindowingMode=undefined mActivityType=home mAlwaysOnTop=undefined mRotation=undefined} themeChanged=0 themeChangedFlags=0 typefaceTimeStamp=0}
          taskDescription: label="null" icon=null iconResource=0 iconFilename=null primaryColor=ffefefef
           backgroundColor=fffafafa
           statusBarColor=0
           navigationBarColor=ffffffff
          launchFailed=false launchCount=0 lastLaunchTime=-3d13h10m31s981ms
          haveState=true icicle=Bundle[mParcelledData.dataSize=7492]
          state=STOPPED stopped=true delayedResume=false finishing=false
          keysPaused=false inHistory=true visible=false sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_REMOVED
          fullscreen=true noDisplay=false immersive=false launchMode=3
          frozenBeforeDestroy=false forceNewConfig=false
          mActivityType=home
           nowVisible=false lastVisibleTime=-6m48s722ms
          connections=com.android.server.wm.ActivityServiceConnectionsHolder@cac0a00
          resizeMode=RESIZE_MODE_RESIZEABLE
          mLastReportedMultiWindowMode=false mLastReportedPictureInPictureMode=false

    Running activities (most recent first):
      TaskRecord{3859883 #5 A=cn.nubia.launcher U=0 StackId=0 sz=1}
        Run #0: ActivityRecord{a912b91 u0 cn.nubia.launcher/com.android.launcher3.Launcher t5}

    mLastPausedActivity: ActivityRecord{a912b91 u0 cn.nubia.launcher/com.android.launcher3.Launcher t5}

activity stack查询与创建总体流程图

activity 堆栈创建与查找.jpg

activity查询过程

这里如果查询到,则将栈顶activity拉到前台,如果没有查询到则新建堆栈(有例外的情况我们不讨论)

ActivityStarter.java
    private ActivityRecord getReusableIntentActivity() {
        // We may want to try to place the new activity in to an existing task.  We always
        // do this if the target activity is singleTask or singleInstance; we will also do
        // this if NEW_TASK has been requested, and there is not an additional qualifier telling
        // us to still place it in a new task: multi task, always doc mode, or being asked to
        // launch this as a new task behind the current one.
       //google注释,相信大家都看得懂
        //是否放在已经存在的task中,这里我们在manifast中添加的属性终于被拉出来用了,相信大家在各种面试中被各种花式问activity的四种启动方式.
        boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
                (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
                || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
        // If bring to front is requested, and no result is requested and we have not been given
        // an explicit task to launch in to, and we can find a task that was started with this
        // same component, then instead of launching bring that one to the front.
       //继续判断复制
        putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
        ActivityRecord intentActivity = null;
      //这里没看懂,这个判断是干啥的
        if (mOptions != null && mOptions.getLaunchTaskId() != -1) {
            final TaskRecord task = mRootActivityContainer.anyTaskForId(mOptions.getLaunchTaskId());
            intentActivity = task != null ? task.getTopActivity() : null;
        } else if (putIntoExistingTask) {
             //属性的感觉来了,launcheMode
            if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
                // There can be one and only one instance of single instance activity in the
                // history, and it is always in its own unique task, so we do a special search.
               intentActivity = mRootActivityContainer.findActivity(mIntent, mStartActivity.info,
                       mStartActivity.isActivityTypeHome());
            } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
           /*
               这个属性看看官方定义,是配合分配使用的
              This flag is only used in split-screen multi-window mode. The new activity will be displayed
              adjacent to the one launching it. This can only be used in conjunction with
             {@link #FLAG_ACTIVITY_NEW_TASK}. Also, setting {@link #FLAG_ACTIVITY_MULTIPLE_TASK} 
              is
             required if you want a new instance of an existing activity to be created.

*/
                // For the launch adjacent case we only want to put the activity in an existing
                // task if the activity already exists in the history.
                intentActivity = mRootActivityContainer.findActivity(mIntent, mStartActivity.info,
                        !(LAUNCH_SINGLE_TASK == mLaunchMode));
            } else {
                // Otherwise find the best task to put the activity in.
                //其他情况
                intentActivity =
                        mRootActivityContainer.findTask(mStartActivity, mPreferredDisplayId);
            }
        }

        if (intentActivity != null
                && (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome())
                && intentActivity.getDisplayId() != mPreferredDisplayId) {
            // Do not reuse home activity on other displays.
            intentActivity = null;
        }

        return intentActivity;
    }

继续查找,这里注意一下,我们是在找activity怎么变成 task了????

findTaskLocked()
    void findTaskLocked(ActivityRecord target, FindTaskResult result) {
       .......................//省略部分代码
        ComponentName cls = intent.getComponent();
        if (info.targetActivity != null) {
            //这里就是拿到class,是不是很熟悉
            cls = new ComponentName(info.packageName, info.targetActivity);
        }

        if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this);

       //for循环,开始大规模寻找啦

        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            final TaskRecord task = mTaskHistory.get(taskNdx);
            if (task.voiceSession != null) {
                // We never match voice sessions; those always run independently.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
                continue;
            }

            //userId不同,一切没有意义继续查
            if (task.userId != userId) {
                // Looking for a different task.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
                continue;
            }

            // Overlays should not be considered as the task's logical top activity.
            final ActivityRecord r = task.getTopActivity(false /* includeOverlays */);
            if (r == null || r.finishing || r.mUserId != userId ||
                     //熟悉的配方
                    r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": mismatch root " + r);
                continue;
            }
 
       .......

            if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Comparing existing cls="
                    + (task.realActivity != null ? task.realActivity.flattenToShortString() : "")
                    + "/aff=" + r.getTaskRecord().rootAffinity + " to new cls="
                    + intent.getComponent().flattenToShortString() + "/aff=" + info.taskAffinity);
            // TODO Refactor to remove duplications. Check if logic can be simplified.
            if (task.realActivity != null && task.realActivity.compareTo(cls) == 0
                    && Objects.equals(documentData, taskDocumentData)) {

                //运气不错,匹配到了哈哈哈

                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
                //dump();
                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
                        "For Intent " + intent + " bringing to top: " + r.intent);
                result.mRecord = r;
                result.mIdealMatch = true;
                break;
            } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
                    affinityIntent.getComponent().compareTo(cls) == 0 &&
                    Objects.equals(documentData, taskDocumentData)) {

                //运气也不错

                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Found matching class!");
                //dump();
                if (DEBUG_TASKS) Slog.d(TAG_TASKS,
                        "For Intent " + intent + " bringing to top: " + r.intent);
                result.mRecord = r;
                result.mIdealMatch = true;
                break;
            } else if {
                ................................
            } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task);  //很悲催,没找到
        }
    }

匹配到堆栈的处理流程

if (reusedActivity != null) {
            ....................
             //熟悉的感觉,这里在判断activity launchmode 是否将其他activity出栈.我们学习的 singleTask就在这里发挥了作用
            if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                    || isDocumentLaunchesIntoExisting(mLaunchFlags)
                    || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
                final TaskRecord task = reusedActivity.getTaskRecord();

                // In this situation we want to remove all activities from the task up to the one
                // being started. In most cases this means we are resetting the task to its initial
                // state.

               //参照google注释,这里做了出栈动作,也就是activity顶部其他activity全部出栈
                final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
                        mLaunchFlags);

                if (top != null) {
                     //new intent 
                    deliverNewIntent(top);
                }
            }
        // 这里的逻辑是在干什么,没有搞清楚
          reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);

  这里巴拉巴拉一大堆我也没看明白

创建堆栈 setTaskFromReuseOrCreateNewTask

还是刚才的函数中,如果没有找reusedActivity则走以下流程,都是代码,细节很多,我也没有搞清楚,不粘贴代码了,直接上调用堆栈,细节还需要看代码掌握

2020-05-08 03:13:11.781 1029-8795/system_process D/ggpstack: java.lang.Throwable
at com.android.server.wm.ActivityStack.createTaskStack(ActivityStack.java:559)
at com.android.server.wm.ActivityStack.(ActivityStack.java:545)
at com.android.server.wm.ActivityDisplay.createStackUnchecked(ActivityDisplay.java:491)
at com.android.server.wm.ActivityDisplay.createStack(ActivityDisplay.java:481)
at com.android.server.wm.ActivityDisplay.getOrCreateStack(ActivityDisplay.java:409)
at com.android.server.wm.ActivityDisplay.getOrCreateStack(ActivityDisplay.java:427)
at com.android.server.wm.RootActivityContainer.getLaunchStack(RootActivityContainer.java:1786)
at com.android.server.wm.ActivityStarter.getLaunchStack(ActivityStarter.java:3259)
at com.android.server.wm.ActivityStarter.computeStackFocus(ActivityStarter.java:3167)
at com.android.server.wm.ActivityStarter.setTaskFromReuseOrCreateNewTask(ActivityStarter.java:2848)
at com.android.server.wm.ActivityStarter.startActivityUnchecked(ActivityStarter.java:2110)
at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1782)
at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:1046)
at com.android.server.wm.ActivityStarter.startActivity(ActivityStarter.java:613)
at com.android.server.wm.ActivityStarter.startActivityMayWait(ActivityStarter.java:1611)
at com.android.server.wm.ActivityStarter.execute(ActivityStarter.java:544)
at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1254)
at com.android.server.wm.ActivityTaskManagerService.startActivityAsUser(ActivityTaskManagerService.java:1182)
at com.android.server.wm.ActivityTaskManagerService.startActivity(ActivityTaskManagerService.java:1159)
at android.app.IActivityTaskManager$Stub.onTransact(IActivityTaskManager.java:1552)
at android.os.Binder.execTransactInternal(Binder.java:1043)
at android.os.Binder.execTransact(Binder.java:1008)

真正创建stack的地方

    ActivityStack(ActivityDisplay display, int stackId, ActivityStackSupervisor supervisor,
            int windowingMode, int activityType, boolean onTop) {
        //一切又回到了最初,我们dumpsys activity中的信息
        //设置display
        mDisplayId = display.mDisplayId;
       //设置type
        setActivityType(activityType);
       //create
        createTaskStack(display.mDisplayId, onTop, mTmpRect2);
       //mode  pip freeform 分屏?
        setWindowingMode(windowingMode, false /* animate */, false /* showRecents */,
                false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
                true /* creating */);
        display.addChild(this, onTop ? POSITION_TOP : POSITION_BOTTOM);
    }

    void createTaskStack(int displayId, boolean onTop, Rect outBounds) {
        final DisplayContent dc = mWindowManager.mRoot.getDisplayContent(displayId);
        if (dc == null) {
            throw new IllegalArgumentException("Trying to add stackId=" + mStackId
                    + " to unknown displayId=" + displayId);
        }
        mTaskStack = new TaskStack(mWindowManager, mStackId, this);
        dc.setStackOnDisplay(mStackId, onTop, mTaskStack);
        if (mTaskStack.matchParentBounds()) {
            outBounds.setEmpty();
        } else {
            mTaskStack.getRawBounds(outBounds);
        }
    }

你可能感兴趣的:(android activity堆栈创建与查找)