It seems you answered your question. You wrote:
So basically I want to change the initial activity, it looks like I have two applications in one application, and when I switch to the second application, I have to clear the activity stack.
I would do it like this:
Create a DispatcherActivity , which is the activity that starts when the application starts. This activity is the main activity of your task and is responsible for starting both A1 and A2 depending ... and DO NOT call finish() on its own (that is: it will be covered by A1 or A2, but it will still be at the root of the stack activity )
In A1 , hook the back key and tell DispatcherActivity to complete as follows:
@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 to root activity ( DispatcherActivity ), and then run DispatcherActivity again with that intention.
In C1 , to start A2 , follow these steps:
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 to root activity ( DispatcherActivity ), and then run DispatcherActivity again with that intention.
In DispatcherActivity , in onCreate() you need to determine what to do based on additional functions in the intent, for example:
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 hook the back key and tell DispatcherActivity to exit using the same onBackPressed() override as in A1 .
Note. I just typed this code, so I did not compile it, and it may not be ideal. Your mileage may vary; -)