How to end activity using the context?

0

I'm developing a game, but I'm stuck on how to finish an activity, since the finish() method does not work.

From this class I want to be able to finalize an activity, from which I call this class, which passed through the context (context).

public class Ventana_Pausa {

public Ventana_Pausa(final Context context) {
    final Dialog dialogo=new Dialog(context);
    dialogo.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialogo.setCancelable(false);
    dialogo.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    dialogo.setContentView(R.layout.pausa);

    ImageButton cerrar=dialogo.findViewById(R.id.IMB_Cerrar);
    ImageButton aceptar=dialogo.findViewById(R.id.IMB_Aceptar);

    aceptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,Menu.class);

            context.startActivity(intent);//aqui puedo ir a otra activity
            //pero aqui nose como finalizar un activity


        }
    });

    cerrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogo.dismiss();
            Jugando.cron.pause();
        }
    });

    dialogo.show();
}

}

Fragment of code of the activity class that I want to finalize

pausa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AudioManager.reproducir){
                    click.start();
                }

                cron.pause();

                new Ventana_Pausa(contexto);//aqui paso el contexto a la esa clase


            }
        });
    
asked by Jorge Ovejero 23.10.2018 в 02:24
source

3 answers

0

With the following it should work to finish an Activity from another context

((Activity) context).finish();
    
answered by 23.10.2018 / 21:26
source
0

You can do it with a context cast:

((Activity) ctx).finish();
    
answered by 23.10.2018 в 09:35
0

The finish () method belongs to class < a href="https://developer.android.com/reference/android/app/Activity"> Activity

Therefore, if you send the context, you will not be able to call finish () in this way:

public myMetodo(final Context context) {
 ...
 ...
   context.finish();
 ...
 ...
}

You must perform a "casting" (conversion of types) to Activity to be able to call it without problem:

public myMetodo(final Context context) {
 ...
 ...
   ((Activity) context).finish();
 ...
 ...
}
    
answered by 04.12.2018 в 01:11