Android
Kotlin

在一連串 startActivity 之後,回到第一個 Activity

More than 1 year has passed since last update.

像是這樣子一連串開啟 activities 之後

A → B → C → D

目前想要達成的是要從 D 直接跳出、回到原本的 A activity

A → B → C → D → A

解法

這時候只要這樣寫就好:

DActivity.kt
// 觸發回到 AActivity 的地方
val intent = Intent(this, AActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)

官方文件

FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

如果加了這個標籤的 Intent 沒有加入 FLAG_ACTIVITY_SINGLE_TOP 的話,似乎會讓指定的目標 Activity 建立一個新的 instance 出來,而不是用到 stack 裡面被存放的那一個

FLAG_ACTIVITY_SINGLE_TOP

If set, the activity will not be launched if it is already running at the top of the history stack.

參考資料