简体   繁体   中英

FLAG_ACTIVITY_SINGLE_TOP not working with startActivityForResult

Is there a way to prevent multiple instances of an activity from being created with startActivityForResult ?

For example:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<TextView>(R.id.button).setOnClickListener {
            startActivityForResult(Intent(this, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            }, 1)
        }
    }
}

Clicking on the button multiple times opens multiple instances of the MainActivity even though I've set FLAG_ACTIVITY_SINGLE_TOP

Edit: Looks like there's a difference in behaviour depending on what Android version I'm running on. Android 8 opens a new Activity but Android 13 does not open a new Activity. How do I ensure that all android versions have the Android 13 behaviour?

you can add android:launchMode="singleTop" in the manifest of your activity.

android:name=".ui.activity.MainActivity"
android:exported="false"
android:screenOrientation="portrait"
android:launchMode="singleTop"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM