处理 Android 返回堆栈
Handling Android back stack
我有一个应用程序,比方说,活动 A、B 和 C。B 可以由 A 以及任何其他应用程序的 activity 启动。但是 C 只能由 B 启动。在按回 C 时,用户导航到 B(没关系)但我在 C 上有一个按钮,按下用户应该导航到 A 或任何其他应用程序的 activity推出B.
要从堆栈中清除 B
并 return 到前一个 Activity,请执行以下操作:
在 C
中,使用 EXTRA 启动 B
:
Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("finish", true);
startActivity(intent);
在这里使用 CLEAR_TOP 和 SINGLE_TOP 确保这将返回到 B
的现有实例,而不是创建一个新实例。
在 B
中,覆盖 onNewIntent()
如下:
@Override
protected void onNewIntent(Intent intent) {
if (intent.hasExtra("finished")) {
// Wants to finish this Activity to return to the previous one
finish();
}
}
注意:仅当 B
在启动 C
时仍在 Activity 堆栈中时才有效(即:启动时它不会调用 finish()
C
).
另一种方法是让 B
使用 startActivityForResult()
启动 C
。在这种情况下,C
可以 return 信息(在 resultCode
或 returned Intent
中)允许 B
确定是否它应该或不应该完成。
我有一个应用程序,比方说,活动 A、B 和 C。B 可以由 A 以及任何其他应用程序的 activity 启动。但是 C 只能由 B 启动。在按回 C 时,用户导航到 B(没关系)但我在 C 上有一个按钮,按下用户应该导航到 A 或任何其他应用程序的 activity推出B.
要从堆栈中清除 B
并 return 到前一个 Activity,请执行以下操作:
在 C
中,使用 EXTRA 启动 B
:
Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("finish", true);
startActivity(intent);
在这里使用 CLEAR_TOP 和 SINGLE_TOP 确保这将返回到 B
的现有实例,而不是创建一个新实例。
在 B
中,覆盖 onNewIntent()
如下:
@Override
protected void onNewIntent(Intent intent) {
if (intent.hasExtra("finished")) {
// Wants to finish this Activity to return to the previous one
finish();
}
}
注意:仅当 B
在启动 C
时仍在 Activity 堆栈中时才有效(即:启动时它不会调用 finish()
C
).
另一种方法是让 B
使用 startActivityForResult()
启动 C
。在这种情况下,C
可以 return 信息(在 resultCode
或 returned Intent
中)允许 B
确定是否它应该或不应该完成。