如何在 Android 中管理 Activity 个实例

How to manage Activity instances in Android

我有一个初始 activity O 和另一个 activity A 我可以 select 去参加活动 A1,A2,A3例如,在每个表格中填写一个表格。所以我走这条路:

O>A>A1>A>A2>A>A3

当我在 A3 时,我想按下后退按钮并再次转到 O 但我将不得不从 A 的每个实例传递(假设我使用 finish()no historyA1,A2,A3 的清单中,因此它们不会出现在堆栈中)

我如何声明 A 在堆栈中只有一个实例(最后一个),这样如果我按两次后退按钮我将再次转到 O

  @Override
public void onBackPressed() {
    Intent intent = new Intent(this,O.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
}

将activityAlaunchMode改为singleTop。正如文档中所述:

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

现在,您可以 finish() activity A1(或使用 up button),而不是从 A -> A1 -> A 开始,这将 return 你到 activity A.

的实例