I have an application where when the user clicks "Back" on the MainActivity
it displays a AlertDialog
on the onBackPressed()
method asking if you really want to quit the application. But I created a new Gerenciar
class to manage, and put all methods there. The problem is that I am not able to insert Finish()
into this class and call MainActivity
. How to proceed?
1 - Code in MainActivity
working:
public void onBackPressed() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Atenção!");
builder.setMessage("Deseja realmente fechar o app?");
builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
alerta = builder.create();
alerta.show();
}
2 - Code in class Gerenciar
not working:
public void Alertar(){
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setTitle("Atenção!");
builder.setMessage("Deseja realmente fechar o app?");
builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
activity.finish(); //Finish() não aceita, e com o 'activity' aceita, mas quebra a aplicação quando executa
}
});
builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
alerta = builder.create();
alerta.show();
}
And I call this method on MainActivity
:
public void onBackPressed() {
final Gerenciar negGer = new Gerenciar(this);
negGer.Alertar();
}