I have a single activity app and I want to manage app exit by pressing twice back button. Now I don't know how and where to manage onBack. Would you please help on this?
Asked
Active
Viewed 330 times
0
-
you can override onbackpressed() method of activity. refer below link https://stackoverflow.com/questions/18337536/android-overriding-onbackpressed – Shree May 18 '21 at 18:01
3 Answers
0
Can do something like this
override fun onBackPressed() {
if (i == 0){
i++
return
}
else {
i = 0
super.onBackPressed()
}
}

Sarah Khan
- 836
- 7
- 11
0
Add this to your Activity
private var doublePressToExit = false
override fun onBackPressed() {
if (doublePressToExit) {
super.onBackPressed()
return
}
this.doublePressToExit = true
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show()
Handler().postDelayed(Runnable { doublePressToExit = false }, 2000) // to reset doublePressToExit to false after 2 sec
}

Anju Kumari
- 43
- 8
0
Implement this code in onBackpressed() function of parent activity
override fun onBackPressed() {
this.supportFragmentManager
.primaryNavigationFragment
?.findNavController()?.popBackStack()
}
primaryNavigationFragment provide the instance of the fragment currently displayed on the screen, and from there, we can pop back Stack
this.supportFragmentManager.popBackStack()
can also work but in that case it destroys the reference of nav direction actions so opening another fragment after closing one would result in a crash with error
Navigation component - cannot be found from the current destination

Keshav
- 173
- 1
- 5