关于 Android 中启动模式的两个问题

Two questions about the launch mode in Android

当我在Activity1中使用startActivityForResult()启动Activity2时,如果Activity1Activity2不在同一个任务栈中,resultCode 是 0(Activity.RESULT_CANCELED).

如果Activity1的launchMode是standard,Activity2的launchMode是singleTask,我得到的resultCode是0。

堆栈中发生了什么?

如果Activity1的launchMode是singleTop并且Activity1使用startActivityForResult()方法启动自身,则栈中有两个Activity1实例。

堆栈中发生了什么?

我自己得到了答案。

第一个问题,我在方法start的注释中找到了答案ActivityForResult(Intent,int,Bundle)。

enter image description here

如下图所示,如果ActivityY结束,显示的Activity可能是ActivityX,所以对于不确定的[=29=,它立即收到取消结果] 仅在 api 低于 20 时发生。

enter image description here

下一个问题,我在源码中找到了答案

ActivityStack topStack = getFocusedStack(); ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop); if (top != null && r.resultTo == null) { Slog.d("DDY", "========------ " ); if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) { if (top.app != null && top.app.thread != null) { if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) { ...... top.deliverNewIntentLocked(callingUid, r.intent);

当Activity尝试自己启动时,r.resultTo不为空,所以它以标准模式启动。