Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaving android app with back button

I want the users of my android app to leave my app when they press back at a certain activity. Can this be done?

like image 494
Sandah Aung Avatar asked Jul 25 '13 08:07

Sandah Aung


People also ask

How do I close an app when my back button is pressed?

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.

What happens when back button is pressed in Android?

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.

How do I close an app with a button?

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.

Does Back button destroy activity?

If the user presses or gestures Back, the current activity is popped from the stack and destroyed.


2 Answers

You can use moveTaskToBack() in the onBackPressed() method to exit app.

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

Hope this helps,

Thanks

like image 80
Muhammad Shujja Avatar answered Oct 14 '22 01:10

Muhammad Shujja


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

like image 21
lovubuntu Avatar answered Oct 14 '22 02:10

lovubuntu