0

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?

user1288005
  • 890
  • 2
  • 16
  • 36
  • Check if my answer works. – Abhimanyu Aug 20 '20 at 17:04
  • From the documentation for `FLAG_ACTIVITY_CLEAR_TOP`: _"The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent()."_ – Michael Aug 20 '20 at 17:13

2 Answers2

1

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.

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
0

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.

David Wasser
  • 93,459
  • 16
  • 209
  • 274