Android: Salir de la aplicación cuando presione el botón atrás


En mi aplicación quiero salir de la aplicación cuando presione el botón atrás, este es mi código:

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure you want to exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton("No", null).show();
    }

Funciona correctamente, pero cuando salgo de la aplicación no sale completamente y muestra la página vacía con el logotipo de mi aplicación y cuando vuelvo a presionar el botón atrás salir de la aplicación, ¿Cómo puedo arreglarlo???

EDITAR:

Uso este código en lugar de arriba , pero mi aplicación sale por completo, pero quiero que se ejecute en segundo plano y no sale por completo, ¿cómo puedo hacerlo?

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure?")
                .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    }
                }).setNegativeButton("no", null).show();
    } 
Author: Elham Gdz, 2013-12-15

11 answers

Cuando presiona atrás y luego termina su actividad actual (por ejemplo, A), ve una actividad en blanco con el logotipo de su aplicación (por ejemplo, B), esto simplemente significa que la actividad B que se muestra después de terminar A todavía está en backstack, y también la actividad A se inició desde la actividad B, por lo que en actividad, debe iniciar la actividad A con banderas como

Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);

Ahora su actividad A está en la parte superior de la pila sin otras actividades de su aplicación en el backstack.

Ahora en la actividad A donde desea implementar onBackPressed para cerrar la aplicación, puede hacer algo como esto,

private Boolean exit = false;
@Override
    public void onBackPressed() {
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }

    }

El Controlador aquí maneja las pulsaciones de retroceso accidentales, simplemente muestra un Toast, y si hay otra pulsación de retroceso dentro de 3 segundos, cierra la aplicación.

 102
Author: Rachit Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-24 09:58:14

Prueba esto:

Intent intent = new Intent(Intent.ACTION_MAIN);
          intent.addCategory(Intent.CATEGORY_HOME);
          intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
          startActivity(intent);
          finish();
          System.exit(0);
 42
Author: Md. Ilyas Hasan Mamun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-18 12:14:25

Tuve el Mismo problema, tengo una LoginActivity y una MainActivity. Si hago clic en el botón atrás en MainActivity, la aplicación tiene que cerrarse. Así que lo hice con el método onBackPressed. este moveTaskToBack () funciona igual que el botón de inicio. Deja la pila trasera como está.

public void onBackPressed() {
  //  super.onBackPressed();
    moveTaskToBack(true);

}
 14
Author: Tara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-20 09:10:04

Significa su actividad anterior en stack cuando inicia esta actividad. Añadir finish(); después de la línea en la que llama a esta actividad.

En toda su actividad anterior. al iniciar una nueva actividad como -

startActivity(I);

Añádase finish(); después de esto.

 5
Author: Kanwaljit Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-15 06:57:26

En mi opinión, Google quiere Android para manejar la gestión de memoria y apagar las aplicaciones. Si debe salir de la aplicación desde el código, podría ser beneficioso pedirle a Android que ejecute el recolector de basura.

@Override
public void onBackPressed(){
    System.gc();
    System.exit(0);
}

También puede agregar finish() al código, pero probablemente sea redundante, si también lo hace System.exit (0)

 3
Author: Matti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-11 08:54:51

Finish no cierra la aplicación, solo cierra la actividad. Si esta es la actividad del lanzador, entonces cerrará tu aplicación; si no, volverá a la actividad anterior.

Lo que puede hacer es usar onActivityResult para activar tantas finish() como sea necesario para cerrar todas las actividades abiertas.

 1
Author: gian1200,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-15 07:07:34

Nadie parece haber recomendado noHistory="true" en manifest.xml para evitar que cierta actividad aparezca después de presionar el botón atrás que por defecto llama al método finish ()

 1
Author: Achmad Naufal Syafiq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 05:08:21

Este funciona para mí.Lo encontré yo mismo combinando otras respuestas

private Boolean exit = false;
@override
public void onBackPressed(){ 
    if (exit) {
        finish(); // finish activity
    } 
    else {
        Toast.makeText(this, "Press Back again to Exit.",
            Toast.LENGTH_SHORT).show();
         exit = true;
         new Handler().postDelayed(new Runnable() {

         @Override
         public void run() {
             // TODO Auto-generated method stub
             Intent a = new Intent(Intent.ACTION_MAIN);
             a.addCategory(Intent.CATEGORY_HOME);
             a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(a);
        }
    }, 1000);
}
 1
Author: Bivin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-08 14:35:11

En lugar de finish() llame a super.onBackPressed()

 0
Author: Shashika,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-15 06:44:33

Para salir de la aplicación al presionar el botón atrás, primero debe borrar todas las actividades principales y luego iniciar el ACTION_MAIN del teléfono android

Por lo tanto, usted tiene que escribir todo este código solo que se menciona a continuación:

Nota: En su caso MainActivity se sustituye por YourActivity

@Override
public void onBackPressed() {

        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.super.onBackPressed();
                        quit();
                    }
                }).create().show();
    }


public void quit() {
        Intent start = new Intent(Intent.ACTION_MAIN);
        start.addCategory(Intent.CATEGORY_HOME);
        start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        start.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(start);
    }
 0
Author: Aman Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-01 13:26:41

Utilice este código solución muy simple

 @Override
    public void onBackPressed() {
      super.onBackPressed(); // this line close the  app on backpress
 }
 -6
Author: bambi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-12 07:08:01