Another alternative would be to show a Toast
/Snackbar
on the first back press asking to press back again to Exit, which is a lot less intrusive than showing an AlertDialog
to confirm if user wants to exit the app.
You can use the DoubleBackPress Android Library
to achieve this with a few lines of code. Example GIF showing similar behaviour.
To begin with, add the dependency to your application :
dependencies {
implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}
Next, in your Activity, implement the required behaviour.
// set the Toast to be shown on FirstBackPress (ToastDisplay - builtin template)
// can be replaced by custom action (new FirstBackPressAction{...})
FirstBackPressAction firstBackPressAction = new ToastDisplay().standard(this);
// set the Action on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
@Override
public void actionCall() {
// TODO : Exit the application
finish();
System.exit(0);
}
};
// setup DoubleBackPress behaviour : close the current Activity
DoubleBackPress doubleBackPress = new DoubleBackPress()
.withDoublePressDuration(3000) // msec - wait for second back press
.withFirstBackPressAction(firstBackPressAction)
.withDoubleBackPressAction(doubleBackPressAction);
Finally, set this as the behaviour on back press.
@Override
public void onBackPressed() {
doubleBackPress.onBackPressed();
}