Change theme
Help
Press space for more information.
Show links for this issue (Shortcut: i, l)
Copy issue ID
Previous Issue (Shortcut: k)
Next Issue (Shortcut: j)
Sign in to use full features.
Vote: I am impacted
Notification menu
Refresh (Shortcut: Shift+r)
Go home (Shortcut: u)
Pending code changes (auto-populated)
View issue level access limits(Press Alt + Right arrow for more information)
Unintended behavior
View staffing
Description
Component used: Activity
Versions used:
androidx.activity: 1.9.3
androidx.navigation: 2.8.4
Devices/Android versions reproduced on:
Pixel emulators API 34 and 35
Samsung S22 API 34
When adding a
OnBackPressedCallback
in anActivity
viaOnBackPressedDispatcher.addCallback
, the callback is incorrectly triggered in favor of lower level default navigation behavior or manual composeBackHandler
calls after backgrounding the app and returning.This issue seems to occur in all of the following cases
Fragment
uses aNavHost
without any customBackHandler
Fragment
uses aNavHost
with a customBackHandler
Fragment
that does not use aNavHost
but uses some other type of "navigation" like a boolean that determines if a further screen or dialog should be shownIn each case I would expect that default
NavController
behavior or manualBackHandler
code would be executed instead of theMainActivity
'sOnBackPressedCallback
. This is what happens without backgrounding the app, but once you background the app and return theMainActivity
code is executed on back press.Example code that reproduces the issue in a couple ways and offers a workaround. See further comments in the code for specific examples
https://github.com/JacobSense/backpress-bug
In the example app you can follow these steps to see the issue
If you require manual back handling, a workaround for BackHandler exists that seems to fix it.
The BackHandler code has this:
If you copy the function but replace
DisposableEffect
withLifecycleResumeEffect
it worksThis is a pretty simple workaround if you need manual back handling. If your goal is the default behavior of navigating back to the start screen of the NavHost and then navigating back, you can add a workaround version of BackHandler to manually implement the default behavior.