I want the users of my android app to leave my app when they press back at a certain activity. Can this be done?
In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so. Otherwise, don't exit.
Depending on the user's Android device, this button might be a physical button or a software button. Android maintains a back stack of destinations as the user navigates throughout your application. This usually allows Android to properly navigate to previous destinations when the Back button is pressed.
Close one app: Swipe up from the bottom, hold, then let go. Swipe up on the app. Close all apps: Swipe up from the bottom, hold, then let go. Swipe from left to right.
If the user presses or gestures Back, the current activity is popped from the stack and destroyed.
You can use moveTaskToBack() in the onBackPressed() method to exit app.
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
Hope this helps,
Thanks
I know this is an old post. But this might be helpful for someone just as it was to me, who wants to implement the same feature in their application.
The solution for identifying double back can be done by calculating the time between two back press. If the difference is less than 2seconds (i.e. 2000 milliseconds) then you can accept that as double back press and exit from the application. Otherwise display the Toast message.
Simple implementation of this would be:
private static long back_pressed;
@Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis())
super.onBackPressed();
else
Toast.makeText(getBaseContext(), "Press once again to exit!",Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
The code can be found in this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With