在我看来,您已经回答了自己的问题。你写道:
所以基本上我想改变启动Activity,就像
我在一个应用程序中有两个应用程序,当我切换到第二个应用程序时,我必须
清除 Activity Stack。
我会这样做:
创建一个DispatcherActivity,它是应用程序启动时启动的活动。此活动是您的任务的根活动,负责启动 A1 或 A2,具体取决于...,而不是自行调用 finish()(即:它将被 A1 或 A2 覆盖,但仍位于活动的根目录堆栈)。
在A1 中,捕获“返回”键并告诉 DispatcherActivity 像这样退出:
@Override
public void onBackPressed() {
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("exit", "true");
startActivity(intent);
}
这会将任务堆栈清除到根 Activity (DispatcherActivity),然后以此意图再次启动 DispatcherActivity。
在C1 中,要启动A2,请执行以下操作:
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("A2", "true");
startActivity(intent);
这会将任务堆栈清除到根 Activity (DispatcherActivity),然后以此意图再次启动 DispatcherActivity。
在DispatcherActivity 中,在onCreate() 中,您需要根据intent 中的额外内容确定要执行的操作,如下所示:
Intent intent = getIntent();
if (intent.hasExtra("exit")) {
// User wants to exit
finish();
} else if (intent.hasExtra("A2")) {
// User wants to launch A2
Intent a2Intent = new Intent(this, A2.class);
startActivity(a2Intent);
} else {
// Default behaviour is to launch A1
Intent a1Intent = new Intent(this, A1.class);
startActivity(a1Intent);
}
在A2 中,捕获“返回”键并告诉 DispatcherActivity 退出使用与A1 中相同的onBackPressed() 覆盖。
注意:我只是输入了这段代码,所以我没有编译它,它可能并不完美。您的里程可能会有所不同;-)