I have a problem clearing the entire activities stack and running a new activity. In my application there is a situation where the user navigates to its profile and close its session. The screens stacks is as follows:
StartActivity (finished automatically, so it does not keep in stack) > MainActivity > UserProfileActivity
When the user click Logout from profile, it should open StartActivity which would show a register screen. The idea is to clear all the activity stacks, so the user cannot keep working afer logout:
UserProfileActivity > StartActivity (and there is no any other in the stack)
I have tried a solution based on IntentCompat makeRestartActivity that is supposed to start the desired activity as it was launched from launcher icon. It works perfectly in Android 4.+, but it does nothing on Android 2.3. The code is as follow (taken from this link):
Intent intentToBeNewRoot = new Intent(UserProfileActivity.this, StartActivity.class);
ComponentName cn = intentToBeNewRoot.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
I saw another solution here, that basically create a intent with some flags:
Intent intent = new Intent(getApplicationContext(), StartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
This seems to work, but after pressing back in StartActivity, it comes back to MainActivity (which is present in the stack), which is supposed to not be available withouth login.
So, is there any way to clear the whole activities stack that works fine with all Android versions?