When going from one screen to another, and do not intend to allow the user to return, use the finish();
after the startActivity(intent);
.
Example:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
So when the user returns to the previous Activity it has already been
completed, it will close the application. If the
Activity remains in the stack.
I observed the following:
@Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), PerguntasActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
If this is the code of the Main screen, the onBackPressed()
is overwriting the default method of the back button that is to end, and is sending to Questionsactivity.class
The second excerpt onResume()
is called when the Activity is opened again, if you are calling it in the Questionasactivity it will finalize the Questionasactivity and return to the Main that remains in the stack. I think it’s not a mistake but a logic problem, but without the rest of the structure of your code it’s a little hard to give you the right answer.
Try it this way:
private void ChecarExit(){
dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("CUIDADO!");
dialog.setMessage("Deseja realmente sair do app?");
dialog.setNegativeButton("Não", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "Requisição cancelada", Toast.LENGTH_LONG).show();
}
});
dialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(getApplicationContext(), PerguntasActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
dialog.create();
dialog.show();
}
Or you can declare a Boolean and manipulate the value of it during this page transition, then perform a check, more or less like this:
@Override
public void onBackPressed() {
if (isTrue()) {
Intent intent = new Intent(getApplicationContext(), PerguntasActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
} else {
finish();
}
}
(In my personal opinion this would be an unnecessary gambit, the best would be to follow as I showed in the previous code)
And what is going on with your described code? Nothing happens? Error?
– Murillo Comino
It is good to put more codes for better understanding of the staff, it is a little confused the way you described. But I added an answer to the first problem I identified.
– SanOli
The program runs smoothly. only error is that instead of ecerrar, back to question Activity
– macielF
@macielF I updated the answer, see if that’s not what’s going on. Again, try to post more complete codes in the questions.
– SanOli