Starting an activity for result with launchMode="singleTop" behaves differently on Android 11 than on Android 12

38 Views Asked by At

I have an Activity with android:launchMode="singleTop".

When I start it for result I get different behavior depending on the Android version:

  • Android 12 and later: The on top of Activity is reused and just gets a call to onNewIntent()
    Expected behavior, because the Activity is declared as singleTop and is already on top of the Activity stack.
  • Android 11 & 10 (and probably lower): A new instance of the Activity is created.
    Unexpected behavior, it behaves as if launchMode was standard.

When I start the Activity regularly (not for result), it works as expected also for Android 11 & 10 (and probably lower).

I couldn't find any mention of this in the Android release notes or migration guides.

Why is that so?

I tried it with and without ActivityCompat. Here is a code example that demonstrates it quite well:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("TestLaunchMode", "onCreate")
        setContent {
            TestLaunchModeTheme {
                Column {
                    val activity = this@MainActivity
                    val options: Bundle? = null
                    val intent = Intent(activity, MainActivity::class.java)
                    Text(
                        text = "Start (compat)",
                        modifier = Modifier.clickable { ActivityCompat.startActivity(activity, intent, options) },
                    )
                    Text(
                        text = "Start",
                        modifier = Modifier.clickable { activity.startActivity(intent, options) },
                    )
                    Text(
                        text = "Start for Result (compat)",
                        modifier = Modifier.clickable { ActivityCompat.startActivityForResult(activity, intent, 1, options) },
                    )
                    Text(
                        text = "Start for Result",
                        modifier = Modifier.clickable { activity.startActivityForResult(intent, 1, options) },
                    )
                }
            }
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.i("TestLaunchMode", "onNewIntent")
    }
}

Because MainActivity has its launchMode set to singleTop in the AndroidManifest I expect the string onCreate to be logged only once when initially starting the App/Activity. All button clicks should log onNewIntent instead.

However on Android 11 & 10 (and probably lower) it logs onCreate when starting the activity for result.

Is there a way to make it work as it is documented? So that I get the same behaviour on Android 11 (and lower) as on Android 12 (and later)?

0

There are 0 best solutions below