Android编程返回键问题:Activity2返回不销毁,需回到Activity1并可再次启动
Got it, let's fix this problem. The issue with moveTaskToBack(true) is that it sends your entire app's task stack to the background, which is why you end up on the home screen instead of Activity1. Here's how you can achieve exactly what you want—going back to Activity1 without destroying Activity2, and being able to re-launch the same Activity2 instance later:
Step 1: Override onBackPressed() in Activity2
Instead of calling the default super.onBackPressed() (which finishes Activity2), we'll explicitly launch Activity1 and keep Activity2 alive in the background. We'll use the FLAG_ACTIVITY_REORDER_TO_FRONT flag to ensure we bring the existing Activity1 instance to the top instead of creating a new one:
@Override public void onBackPressed() { Intent intent = new Intent(this, Activity1.class); // Bring the existing Activity1 instance to the top of the stack intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent); // Skip super.onBackPressed() to avoid finishing Activity2 }
Step 2: Launch Activity2 correctly from Activity1
When you want to open Activity2 again from Activity1, use the same FLAG_ACTIVITY_REORDER_TO_FRONT flag. This will bring the existing Activity2 instance (that's been running in the background) back to the foreground instead of creating a new instance:
// In Activity1, when you want to launch Activity2 Intent intent = new Intent(this, Activity2.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent);
Why this works
- When you press back in Activity2, we launch Activity1 (reusing its existing instance) and leave Activity2 in the task stack (in a paused state, not destroyed).
- When you re-launch Activity2 from Activity1, the flag tells Android to pull the existing Activity2 instance to the top of the stack, so you pick up right where you left off.
Important Notes
- You don't need to change the launch mode in the AndroidManifest.xml for this approach, but if you want to enforce single instances more strictly, you can set
launchMode="singleTask"for Activity2 (though the flag approach is usually sufficient). - Make sure you don't call
finish()anywhere in Activity2's back press logic—this would destroy the instance, which we're trying to avoid.
内容的提问来源于stack exchange,提问作者Faizan Khan

