3

Estoy intentando cerrar la app.

Tengo un error al final del código (la línea está comentada):

public class VistaJuego extends SurfaceView {
  private Rect playerr;
  private Rect rectangleObject;
  private Rect obsr;

  private int ySuelo;
  private int anchoPantalla;
  private boolean isFirstDraw = true;
  Paint paint = new Paint();

  HiloJuego hiloJuego;
  private SurfaceHolder holder;

  public static int globalxSpeed = 15;

  Bitmap playerbmp;
  Bitmap coinbmp;
  Bitmap canionbmp;
  Bitmap bloquebmp;
  Bitmap nubebmp;
  Bitmap suelobmp;

  private List < ObjetoJuego > listaObjetos = new ArrayList < ObjetoJuego > ();
  private List < Player > player = new ArrayList < Player > ();
  private List < Suelo > listaSuelo = new ArrayList < Suelo > ();

  public static int coinsCollected = 0;
  public static int score = 0;
  public static int highScore = 6000;

  public VistaJuego(Context context) {
    super(context);

    hiloJuego = new HiloJuego(this);

    holder = getHolder();
    holder.addCallback(new SurfaceHolder.Callback() {
      @Override
      public void surfaceCreated(SurfaceHolder arg0) {
        hiloJuego.setRunning(true);
        hiloJuego.start();

      }

      @Override
      public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

        score += 5;

        if (score > highScore) {
          highScore = score;
        }

      }

      @Override
      public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

      }
    });

    playerbmp = BitmapFactory.decodeResource(getResources(), R.mipmap.mario);
    coinbmp = BitmapFactory.decodeResource(getResources(), R.mipmap.coins);
    canionbmp = BitmapFactory.decodeResource(getResources(), R.mipmap.canions);
    bloquebmp = BitmapFactory.decodeResource(getResources(), R.mipmap.bloque);
    nubebmp = BitmapFactory.decodeResource(getResources(), R.mipmap.nube);
    suelobmp = BitmapFactory.decodeResource(getResources(), R.mipmap.suelo);

    /*CARGANDO A MARIO*/
    player.add(new Player(this, playerbmp, 50, 50));

    /* AÑADIENDO MONEDAS */
    listaObjetos.add(new Coin(this, coinbmp, 400, 900));
    listaObjetos.add(new Coin(this, coinbmp, 250, 800));
    listaObjetos.add(new Coin(this, coinbmp, 1000, 850));
    listaObjetos.add(new Coin(this, coinbmp, 1600, 800));
    listaObjetos.add(new Coin(this, coinbmp, 1700, 850));
    listaObjetos.add(new Coin(this, coinbmp, 1800, 850));
    listaObjetos.add(new Coin(this, coinbmp, 1900, 550));
    listaObjetos.add(new Coin(this, coinbmp, 2100, 900));
    listaObjetos.add(new Coin(this, coinbmp, 2300, 850));
    listaObjetos.add(new Coin(this, coinbmp, 3000, 850));
    listaObjetos.add(new Coin(this, coinbmp, 3100, 850));
    listaObjetos.add(new Coin(this, coinbmp, 3200, 850));
    listaObjetos.add(new Coin(this, coinbmp, 3400, 900));
    listaObjetos.add(new Coin(this, coinbmp, 3500, 800));
    listaObjetos.add(new Coin(this, coinbmp, 4000, 850));
    listaObjetos.add(new Coin(this, coinbmp, 4100, 850));
    listaObjetos.add(new Coin(this, coinbmp, 4500, 900));
    listaObjetos.add(new Coin(this, coinbmp, 4800, 900));
    listaObjetos.add(new Coin(this, coinbmp, 5000, 800));
    listaObjetos.add(new Coin(this, coinbmp, 5500, 800));
    listaObjetos.add(new Coin(this, coinbmp, 5600, 850));
    listaObjetos.add(new Coin(this, coinbmp, 5700, 850));
    listaObjetos.add(new Coin(this, coinbmp, 7500, 900));
    listaObjetos.add(new Coin(this, coinbmp, 7800, 900));
    listaObjetos.add(new Coin(this, coinbmp, 7900, 800));
    listaObjetos.add(new Coin(this, coinbmp, 9000, 800));
    listaObjetos.add(new Coin(this, coinbmp, 9600, 850));
    listaObjetos.add(new Coin(this, coinbmp, 9800, 850));
    listaObjetos.add(new Coin(this, coinbmp, 10000, 900));
    listaObjetos.add(new Coin(this, coinbmp, 10100, 900));
    listaObjetos.add(new Coin(this, coinbmp, 10300, 800));

    /*AÑADIENDO CAÑONES*/
    listaObjetos.add(new Canion(this, canionbmp, 2300, 800));
    listaObjetos.add(new Canion(this, canionbmp, 2600, 900));
    listaObjetos.add(new Canion(this, canionbmp, 2900, 950));
    listaObjetos.add(new Canion(this, canionbmp, 4000, 800));
    listaObjetos.add(new Canion(this, canionbmp, 4500, 900));
    listaObjetos.add(new Canion(this, canionbmp, 5500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 6000, 950));
    listaObjetos.add(new Canion(this, canionbmp, 6500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 7000, 700));
    listaObjetos.add(new Canion(this, canionbmp, 7200, 800));
    listaObjetos.add(new Canion(this, canionbmp, 7500, 900));
    listaObjetos.add(new Canion(this, canionbmp, 8000, 700));
    listaObjetos.add(new Canion(this, canionbmp, 8500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 8000, 950));
    listaObjetos.add(new Canion(this, canionbmp, 9500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 10000, 700));
    listaObjetos.add(new Canion(this, canionbmp, 10500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 10800, 950));
    listaObjetos.add(new Canion(this, canionbmp, 11500, 800));
    listaObjetos.add(new Canion(this, canionbmp, 11800, 950));
    listaObjetos.add(new Canion(this, canionbmp, 12000, 800));

    /*AÑADIENDO BLOQUES*/
    listaObjetos.add(new Bloque(this, bloquebmp, 500, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 600, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 700, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 1200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 1300, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 1400, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 2000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 2100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 2200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 5000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 5100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 5200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 6000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 6100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 6200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 7000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 7100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 7200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 9000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 9100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 9200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 11000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 11100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 11200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 15000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 15100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 15200, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 18000, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 18100, 850));
    listaObjetos.add(new Bloque(this, bloquebmp, 18200, 850));

    /*AÑADIENDO NUBES*/
    listaObjetos.add(new Nube(this, nubebmp, 100, 200));
    listaObjetos.add(new Nube(this, nubebmp, 150, 300));
    listaObjetos.add(new Nube(this, nubebmp, 180, 250));
    listaObjetos.add(new Nube(this, nubebmp, 190, 250));
    listaObjetos.add(new Nube(this, nubebmp, 1000, 250));
    listaObjetos.add(new Nube(this, nubebmp, 1400, 100));
    listaObjetos.add(new Nube(this, nubebmp, 1420, 100));
    listaObjetos.add(new Nube(this, nubebmp, 1440, 100));
    listaObjetos.add(new Nube(this, nubebmp, 1500, 250));
    listaObjetos.add(new Nube(this, nubebmp, 1550, 100));
    listaObjetos.add(new Nube(this, nubebmp, 1600, 100));
    listaObjetos.add(new Nube(this, nubebmp, 1700, 250));
    listaObjetos.add(new Nube(this, nubebmp, 2000, 100));
    listaObjetos.add(new Nube(this, nubebmp, 2320, 100));
    listaObjetos.add(new Nube(this, nubebmp, 2440, 100));
    listaObjetos.add(new Nube(this, nubebmp, 2500, 250));
    listaObjetos.add(new Nube(this, nubebmp, 2550, 100));
    listaObjetos.add(new Nube(this, nubebmp, 2700, 100));
    listaObjetos.add(new Nube(this, nubebmp, 3000, 100));
    listaObjetos.add(new Nube(this, nubebmp, 3200, 250));
    listaObjetos.add(new Nube(this, nubebmp, 3550, 100));
    listaObjetos.add(new Nube(this, nubebmp, 3700, 100));
    listaObjetos.add(new Nube(this, nubebmp, 3900, 100));

    this.paint.setColor(Color.WHITE);
  }

  public boolean onTouchEvent(MotionEvent event) {

    player.get(0).ontouch();

    return false;
  }

  private void firstDraw(Canvas canvas) {
      this.ySuelo = this.getHeight() - 64;
      this.anchoPantalla = this.getWidth();

      this.isFirstDraw = false;
    }
    /******************************************************  
    public void finJuego(){
           Intent intent = new Intent(getContext(),FinJuego.class);
           getContext().startActivity(intent);
       }**********************************************************/

  public void aniadirSuelo() {
    listaSuelo.add(new Suelo(this, suelobmp, 0, 0));
  }

  public void update() {
    score += 5;

    if (score > highScore) {
      highScore = score;
    }
  }

  protected void onDraw(Canvas canvas) {
    /* if (this.isFirstDraw) {
            firstDraw(canvas);
        }
    */
    update();
    canvas.drawColor(Color.CYAN);
    aniadirSuelo();

    Paint textpaint = new Paint();
    textpaint.setTextSize(40);
    canvas.drawText("Score: " + (toString().valueOf(score)), 0, 40, textpaint);
    canvas.drawText("High Score: " + (toString().valueOf(highScore)), 0, 80, textpaint);
    canvas.drawText("Coins: " + (toString().valueOf(coinsCollected)), 0, 120, textpaint);

    player.get(0).onDraw(canvas);

    ObjetoJuego objeto;
    playerr = player.get(0).GetBounds();

    for (Suelo ssuelo: listaSuelo) {
      ssuelo.onDraw(canvas);
    }

    for (int i = 0; i < listaObjetos.size(); i++) {
      objeto = listaObjetos.get(i);
      objeto.onDraw(canvas);
      rectangleObject = objeto.GetBounds();

      if (objeto.comprobarColision(playerr)) {
        if (objeto instanceof Coin) {
          /*objeto.ocultar();*/
          listaObjetos.remove(i);
          score += 500;
          coinsCollected += 1;
        } else if (objeto instanceof Bloque) {
          /* objeto.ocultar();*/
          listaObjetos.remove(i);
        } else if (objeto instanceof Canion) {
          //EL ERROR ESTÁ AQUÍ!! --->       finJuego();
        }
      }
    }
  }
}
4
  • Bienvenido a Stack Overflow en Español, puede tratar de mejorar su pregunta mirando este enlace, Por favor, aclara qué dificultades tienes con el código que has colocado en tu pregunta. el 23 ene. 2017 a las 21:23
  • 2
    Hola! Lo que necesitas saber de StackOverflow es que debes ser específico y agregar código, haz cumplido con la segunda condición, ahora ve por la primera, es sólo una recomendación :) el 23 ene. 2017 a las 21:44
  • En vez de comentar el error, no sería mas útil de compartir la excepción que te sale en el depurador? el 24 ene. 2017 a las 2:20
  • He agregado una respuesta espero te ayude. @user28418
    – Jorgesys
    el 24 ene. 2017 a las 16:44

1 respuesta 1

2

Para finalizar una aplicación desde una clase que es la Activity principal se realiza simplemente con el método:

finish();

Si estas dentro de un Fragment y La Activity que lo contiene es la principal, puedes llamar el método finish() desde el Fragment.

getActivity().finish();

desafortunadamente esto no resuelve el estar en otra Activity que no es la principal y cerrar todas para terminar la aplicación.

Afortunadamente actualmente se tiene el método finishAffinity() el cual se agrego en la API 16 y el cual nos permite terminar todas las Activities

finishAffinity() Termine esta actividad así como todas las actividades inmediatamente debajo de ella en la tarea actual que tengan la misma afinidad.

En cuanto a la clase que comentas en tu pregunta es un caso diferente, ya que esta clase no extiende de Activity o Fragment, lo que puedes realizar en este caso es lo siguiente, crear un método estático para obtener la instancia de la Activity:

public static MainActivity thisActivity;

    public MainActivity() {
        thisActivity = this;
    }
    public static MainActivity getInstance() {
        return thisActivity;
    }

y en tu clase llamar este método y al mismo tiempo llamar finishAffinity():

 MainActivity.getInstance().finishAffinity();

Con esto lograras cerrar la aplicación.


No recomiendo el uso de

System.exit(0);

Ya que reinicia la aplicación con una actividad menos en la pila. Por ejemplo si llama ActivityB de ActivityA y System.exit(0) se llama en ActivityB, entonces la aplicación se eliminará y se iniciará inmediatamente con sólo una actividad ActivityA, sin embargo esto no resolvería cerrar toda la aplicación.

No recomiendo el uso de :

android.os.Process.killProcess(android.os.Process.myPid());

Esto puede no funcionar en varios sistemas operativos, lo he usado para cerrar aplicaciones portadas a Blackberry 10+ donde funciona sin problema.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.