Seems to me you've answered your own question. You wrote:
So it is basically I want to change the starting Activity, it is like
I have two Apps in one App and when I flip to the second App I have to
clear the Activity Stack.
I would do it this way:
Create a DispatcherActivity
which is the activity that gets launched when the application is started. This Activity is the root activity of your task and is responsible for launching either A1 or A2 depending... and NOT call finish()
on itself (ie: it will be covered by A1 or A2 but still be at the root of the activity stack).
In A1
, trap the "back" key and tell the DispatcherActivity to quit like this:
@Override
public void onBackPressed() {
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("exit", "true");
startActivity(intent);
}
This will clear the task stack down to the root activity (DispatcherActivity
) and then start the DispatcherActivity
again with this intent.
In C1
, to launch A2
, do the following:
Intent intent = new Intent(this, DispatcherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addExtra("A2", "true");
startActivity(intent);
This will clear the task stack down to the root activity (DispatcherActivity
) and then start the DispatcherActivity
again with this intent.
In DispatcherActivity
, in onCreate()
you need to determine what to do based on the extras in the intent, like this:
Intent intent = getIntent();
if (intent.hasExtra("exit")) {
// User wants to exit
finish();
} else if (intent.hasExtra("A2")) {
// User wants to launch A2
Intent a2Intent = new Intent(this, A2.class);
startActivity(a2Intent);
} else {
// Default behaviour is to launch A1
Intent a1Intent = new Intent(this, A1.class);
startActivity(a1Intent);
}
In A2
, trap the "back" key and tell the DispatcherActivity to quit using the same override of onBackPressed()
as in A1
.
Note: I just typed this code in, so I've not compiled it and it may not be perfect. Your mileage may vary ;-)