I am writing a application where I am dealing with 4 activities, let's say A, B, C & D. Activity A invokes B, B invokes C, C invokes D. On each of the activity, I have a button called "home" button. When user clicks on home button in any of the B, C, D activities, application should go back to A activity screen ?
How to simulate "home" button in this case ?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have given text view, when the user click on text view, it will open new activity.
To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.
button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(D.this, A.class)); } });
Declare A in your manifest with the android:launchMode="singleTask"
. This way, when you call startActivity()
from your other activies, and A is already running, it will just bring it to the front. Otherwise it'll launch a new instance.
The only problem i see using android:launchMode="singleTask"
is whenever you minimize app and start app by pressing app icon again then app start from scratch and doesn't acquire its state. so i have opted to use
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
which will keep only one instance and clear all activities on top of that.
Intent intent = new Intent( context, MyActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ); current_activity.startActivity( intent );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With