Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ask user to exit application on back press in android?

Tags:

android

back

I have a list of activities in my app.

If the user is on home activity a toast will appear "Asking the user to press again to exit."

But if the user navigates to 2nd or 3rd activity and again goes back to home activity my code fails to show the toast.

I want every-time the user is on home activity a toast should appear.

I know there is some mistake in my logic. Could someone help me out please.

This is the code for back pressed

    @Override
    public void onBackPressed() {
    i++;
    if (i == 1) {
        Toast.makeText(HomeActivity.this, "Press back once more to exit.",
                Toast.LENGTH_SHORT).show();
    } else if(i>1) {
        finish();
        super.onBackPressed();
    }
}
like image 804
WISHY Avatar asked Dec 01 '22 17:12

WISHY


1 Answers

This is how I do back button exit and it works always. It also handles un-intentional back presses by giving a 3 sec. wait time for double back press, if users presses back within 3 secs, it exists the app.

private boolean exit = false;
@Override
public void onBackPressed() {
    if (exit)
        Home.this.finish();
    else {
        Toast.makeText(this, "Press Back again to Exit.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);

    }

}
like image 131
Rachit Mishra Avatar answered Dec 09 '22 18:12

Rachit Mishra