How to call Finish () from a separate class?

1

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();
    } 
    
asked by anonymous 23.02.2017 / 14:17

1 answer

0

You need to call the finish() method this way below:

((Activity) context).finish();

A basic example:

public class classA{

    Context context;

    public classA(Context context){
        this.context = context;
    }

    void exemploMetodo(){
        ((Activity)context).finish();
    }
}

Adapting to your code:

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) context).finish();

        }
    });
    builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {}
    });
    alerta = builder.create();
    alerta.show();
}
    
23.02.2017 / 14:31