Android: Finish all activity and take user to home without loading home

190 views Asked by At

There is home icon on app's app bar at top and I want to finish all activities and take user to home page. But, I don't want home page to be re-created.

I have already tried following but it re-creates home page and I don't want it

 fun goToHomePage() {
    val homeIntent = Intent(activity, HomeActivity::class.java)
    homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
    startActivity(intent)
 }

    <activity
        android:name="HomeActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar"/>
   

Re-creating home put pressure on our backend and we don't want that. How to do achieve it?

2

There are 2 answers

6
Abhimanyu On

For HomeActivity use "singleTop" launchmode.

In AndroidManifest:

<activity 
    android:launchMode="singleTop"
    android:name="HomeActivity"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme.NoActionBar" />  

Reference: https://developer.android.com/guide/topics/manifest/activity-element#lmode

Edit:

From the docs:

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

Use onNewIntent() to handle your scenario.

0
David Wasser On

To return to the existing instance of HomeActivity, just do this:

val homeIntent = Intent(activity, HomeActivity::class.java)
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)

This will clear all other activities from the stack back to the existing instance of HomeActivity.

HomeActivity.onNewIntent() will be called.