完成另一项活动的活动

假设我有3个活动A,B和C. A导致B导致C.我希望能够在A和B之间来回移动但是我想在C开始时完成A和B. 我理解如何在通过意图启动C时关闭B但是如何在C启动时关闭A?

打开C acitivity时使用此标志。

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

这将清除C之上的所有活动。

由于A是您的根(起始)活动,因此请考虑使用A作为调度程序。 当您想要启动C并在之前(下)完成所有其他活动时,请执行以下操作:

 // Launch ActivityA (our dispatcher) Intent intent = new Intent(this, ActivityA.class); // Setting CLEAR_TOP ensures that all other activities on top of ActivityA will be finished intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add an extra telling ActivityA that it should launch ActivityC intent.putExtra("startActivityC", true); startActivity(intent); 

ActivityA.onCreate()执行此操作:

 super.onCreate(); Intent intent = getIntent(); if (intent.hasExtra("startActivityC")) { // Need to start ActivityC from here startActivity(new Intent(this, ActivityC.class)); // Finish this activity so C is the only one in the task finish(); // Return so no further code gets executed in onCreate() return; } 

这里的想法是您使用FLAG_ACTIVITY_CLEAR_TOP启动ActivityA(您的调度程序),以便它是任务中唯一的活动,并告诉它您希望它启动哪些活动。 然后它将启动该活动并完成自己。 这将使您只在堆栈中使用ActivityC。