Q:

Finish all side activities but do not finish the main activity

I have this app where the user can open the activites like this:
MainActivity -> ActivityB -> ActivityC -> ActivityD
Now, I want the user to be able to return normally from:
MainActivity <- ActivityB <- ActivityC
Though, if went for ActivityD, I want it to close everything up to the MainActivity:
MainActivity <- ActivityD
Is this the right approach to accomplishing what I want:
https://stackoverflow.com/a/14785924/10532911
Edit: I originally thought that /14785924/10532911 applies as a solution. Though, I did not need results at all. The solution below is the one for my case.

A:

In ActivityD, to return to MainActivity, use a code like this:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

Using the flag CLEAR_TOP will finish all activities in the stack that are on top of MainActivity. 
In the example you gave, this will finish ActivityD, ActivityC and ActivityB. Using the flag SINGLE_TOP will make sure that this will return control to the existing instance of MainActivity (ie: it won't create a new instance of MainActivity).
Edit:
@Override
public void onBackPressed() {

   // place the code above here, to use back button to switch to new activity
}

