Lately the applications that come out, have incorporated the fact of pressing the back button twice físico como virtual
to exit the app, showing a message `Press one more time to exit.
I have the following implemented:
In MainActivity
main I declare the canExitApp
global variable to set if it has ever been pressed.
public class MainActivity extends AppCompatActivity {
...
private boolean canExitApp = false;
...
And in the method I onBackPressed
check the state variable if it is a true
it exits the app if it is in it false
shows the message with a toast
.
@Override
public void onBackPressed() {
//super.onBackPressed();
if (!canExitApp) {
canExitApp = true;
Toast.makeText(this, getString(R.string.app_back_pressed_exit), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
canExitApp = false;
}
}, 2000);
} else {
super.onBackPressed();
}
}
It would be allowing the user X seconds to press to exit again.
Right now it only works on activitys.
How can I add support for 'fragments', so that if there are none left on the stack, it detects if it wants to exit altogether?
If I use, for example, a side menu that loads fragments, I navigate between them, taking into account that if there is one in the stack, it will show it, until it reaches 0, I want the double-click to exit to work.
I prefer not to use threads to change a variable, but rather to use time based comparisons
System.currentTimeMillis()
. The following code gives you 2 seconds to press BACK againIn case someone has this problem in android but with Fragments You just have to check that the stack is empty to proceed to check the double back
I just found a library for
Presione de nuevo para cerrar
: Shutdown library . Its use is so simple that it should only be added in the eventonBackPressed
:It will show the message
Press back again to close
and the user has 3 seconds, that if he presses the back button again, the app will close.The text can be personalized with:
Based on the Shutdown library I have created the following class
Its use
You can try this: