Search code examples
androidback

Ask user to exit application on back press in android?


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();
    }
}

Solution

  • You must set i = 0 when navigate back to HomeActivity.

    So, in your HomeActivity.java set i = 0 inside OnResume()

    Like this

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        i = 0;
    }