Android:完成所有活动并将用户带回家而不带回家

问题描述

应用顶部的应用栏上有主页图标,我想完成所有活动并将用户带到主页。但是,我不希望重新创建主页。

我已经尝试过跟踪,但是它会重新创建主页,我不想要

 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"/>
   

重建家园给我们的后端带来了压力,我们不希望这样。如何做到这一点?

解决方法

对于HomeActivity,请使用"singleTop"启动模式。

在AndroidManifest中:

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

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

编辑:

从文档中

如果活动的实例已经存在于目标的顶部 任务,系统通过调用将该意图路由到该实例 其onNewIntent()方法,而不是创建 活动。

使用onNewIntent()处理您的情况。

,

要返回到HomeActivity的现有实例,只需执行以下操作:

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

这会将所有其他活动从堆栈中清除回HomeActivity的现有实例。

HomeActivity.onNewIntent()将被呼叫。