After having to implement the same behaviour many times, decided to come up with an android library for it. DoubleBackPress Android Library
, takes care of all the hassle, and provides easy templates to work with.
Example GIF of similar behavioural requirements.
First, add the dependecy to your application :
dependencies {
implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}
Now, the implementation :
// set the Action to occur on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
@Override
public void actionCall() {
// TODO : your code to exit the application
}
};
// setup DoubleBackPress behaviour
DoubleBackPress doubleBackPress = new DoubleBackPress()
.withDoublePressDuration(3000) //msec - timeout
.withDoubleBackPressAction(doubleBackPressAction);
@Override
public void onBackPressed() {
doubleBackPress.onBackPressed();
}