Just use FLAG_ACTIVITY_CLEAR_TOP
When user clicks button:
Intent intent = new Intent(ActivityD.this, ActivityB.class);
Intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
When user presses back:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(ActivityD.this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
This code will take the user to first activity.The activity won't be recreated because of FLAG_ACTIVITY_SINGLE_TOP
. When activity is already on back stack the onNewIntent() will be invoked in which you can use data from intent for example.
If you want such behaviors as default for yours activities put these flags to android manifest into activity declarations.