WISHY WISHY - 1 year ago 83
Android Question

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

public void onBackPressed() {
if (i == 1) {
Toast.makeText(HomeActivity.this, "Press back once more to exit.",
} else if(i>1) {


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

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

Like this

protected void onResume() {
    // TODO Auto-generated method stub
    i = 0;