How to use onbackpressed properly in my app

Viewed 83

I have 2 activities A and B, inside the B activity I have 4 fragments

What I need in my app Inside the 4th fragment I have signout option, after signout it goes to A activity then press back button in my mobile the app will be closed fully.

What problem I'm facing in my app After I click the signout it goes to A activity then I press back button it again goes to the 4th fragment(signout page) then again I click back only my app fully gets closed.

Inside B activity I added this for onbackpressed

 override fun onBackPressed() {
    if (supportFragmentManager.backStackEntryCount > 0) {
        super.onBackPressed()
    } else {
        finish()
    }
}
1 Answers

If you want to close full app then you need to finish all activities from stack.

To finish all activities use finishAffinity() method.

From Activity - finishAffinity()

From Fragment - requireActivity().finishAffinity()

Related