How to close app by back button double click

I want close app by android back button

First, click back button, open dialog

In this state, I want both dialog button and back button to close the app
However, dialog button works but back button doesn’t work

Flow of the code

initialize variable flag to false

click back button 1st time
skip if ~~
execute else (show dialog and set flag to true)

click back button 2nd time ← not work
execute if (close app)

Is there any way to close dialog by touching outside of dialog?