Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

when click back button, the app crashs after a seceond

I have customized back button. when I click on it, the application crashes after a second.
here is the code:
error log

    private var mBackPressed: Long = 0
    private val timeInterval = 2000



    private fun configBackPress() {
        requireActivity().onBackPressedDispatcher.addCallback(this, true) {
            when {
                mBackPressed + timeInterval > System.currentTimeMillis() -> {
                   
                    requireActivity().onBackPressedDispatcher.onBackPressed()
                }
                else -> {
                    Snackbar.make(
                        requireActivity().findViewById(android.R.id.content),
                        getString(R.string.press_once_again_back_button_to_exit),
                        Snackbar.LENGTH_SHORT
                    )
                        .setAnchorView(viewBinding.vSnackBarHelper)
                        .show()

                    mBackPressed = System.currentTimeMillis()
                }
            }
        }
    }

when the user click two times on back button, the back should work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

before calling requireActivity().onBackPressedDispatcher.onBackPressed(). you should set isEnabled to false because if we go through the onBackPressed source code we see:
enter image description here

it looks for active callbacks and if found any calls them and returns. that’s what makes the loop.

your code should be:

isEnabled = false
requireActivity().onBackPressedDispatcher.onBackPressed()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading