Domanda

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();
    }
}
È stato utile?

Soluzione 2

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

Altri suggerimenti

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

    }

}

All right whenever you are calling another Activity you need to set i=0 before each startActivity(xyz) in your HomeActivity. I think i should solve your issue, if it does not just let me know.

A nice and simple solution using snackbar

LinearLayout mLayout;
Snackbar mSnackbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLayout = findViewById(R.id.layout_main);
    mSnackbar = Snackbar.make(mLayout,"Press again to exit", Snackbar.LENGTH_SHORT);
}

@Override
public void onBackPressed() {
    if (mSnackbar.isShown()) {
        super.onBackPressed();
    } else {
        mSnackbar.show();
    }
}

Instead use a AlertDialogBox in onBackPressed method of your homeActivity .. and finish() the activity when Yes is pressed.

  @Override
public void onBackPressed()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Exit");
    builder.setMessage("Are You Sure?");

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
            }
        });

    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

I would suggest to used alert popup in this case. but in your code also it can work as follows:

int i = 1;


@Override
        public void onBackPressed() {       
            if (i == 1) {
                Toast.makeText(getApplicationContext(), "Press back once more to exit.",
                        Toast.LENGTH_SHORT).show();


            } else if(i>1) {
                finish();
            }
            i++;
        }

Logic :

  1. Create a variable with initial value as 0

  2. set the value to 1 after showing toast, so that the value can enter if statement if pressed again

  3. create an handler with specified delay so that if user does not press back again in specified it changes value to 0 which prevents from entering in IF condition.

\ int x=0;

 @Override
 public void onBackPressed() {

    if(x==1) {
        super.onBackPressed();
        return;
    }
    Toast.makeText(this,"Press Again to Exit!!",Toast.LENGTH_SHORT).show();
    x=1;

    android.os.Handler handler=new android.os.Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            x = 0;
        }
    }, 2000);  //2 sec delay

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top