android presionando el botón atrás debe salir de la aplicación


Cuando un usuario presiona el botón atrás en una intent, la aplicación debe salir. ¿Cómo puedo asegurarme de que la aplicación se cierra cuando se presiona el botón atrás?

Author: Erik Schierboom, 2010-03-01

10 answers

Inmediatamente después de iniciar una nueva actividad, usando startActivity, asegúrese de llamar a finish() para que la actividad actual no esté apilada detrás de la nueva.

EDITAR Con respecto a su comentario:

Lo que estás sugiriendo no es particularmente cómo funciona el flujo de la aplicación Android, y cómo los usuarios esperan que funcione. Lo que puede hacer si realmente lo desea, es asegurarse de que cada startActivity que conduce a esa actividad, es un startActivityForResult y tiene un onActivityResult oyente que comprueba si hay un código de salida y lo devuelve. Puedes leer más sobre eso aquí. Básicamente, use setResult antes de terminar una actividad, para establecer un código de salida de su elección, y si su actividad padre recibe ese código de salida, lo establece en esa actividad, y termina esa, etc...

 38
Author: David Hedlund,
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
2010-03-01 09:29:15

En mi Actividad de Inicio anulo el "onBackPressed" para:

@Override
public void onBackPressed() {
   Intent intent = new Intent(Intent.ACTION_MAIN);
   intent.addCategory(Intent.CATEGORY_HOME);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
 }

Así que si el usuario está en la actividad de inicio y presiona atrás, va a la pantalla de inicio.

Tomé el código de Yendo a la pantalla de inicio Programáticamente

 82
Author: Hugo,
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-05-23 12:34:23

Una mejor experiencia de usuario:

/**
 * Back button listener.
 * Will close the application if the back button pressed twice.
 */
@Override
public void onBackPressed()
{
    if(backButtonCount >= 1)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
        backButtonCount++;
    }
}
 24
Author: Vlad Spreys,
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
2015-10-01 14:55:05

¿Por qué el usuario no pulsaría el botón de inicio? Luego, pueden salir de tu aplicación de cualquiera de tus actividades, no solo de una específica.

Si le preocupa que su aplicación continúe haciendo algo en segundo plano. Asegúrese de detenerlo en los comandos onPause y onStop relevantes (que se activarán cuando el usuario presione Inicio).

Si su problema es que desea que la próxima vez que el usuario haga clic en su aplicación para que comience de nuevo desde el principio, le recomiendo poner algún tipo de elemento de menú o botón de interfaz de usuario en la pantalla que lleva al usuario de nuevo a la actividad inicial de su aplicación. Como el pájaro de twitter en la aplicación oficial de twitter, etc.

 2
Author: Eric,
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
2010-10-29 17:21:09

Use onBackPressed método

@Override
public void onBackPressed() {
    finish();
    super.onBackPressed();
}

Esto resolverá su problema.

 2
Author: Akila,
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-03-21 09:27:29

La aplicación solo saldrá si no hay actividades en el back stack. ASÍ que añade esta línea en tu manifiesto android:noHistory="true" a todas las actividades que no quieras volver a apilar.Y luego para cerrar la aplicación llame al finish () en el onBackPressed

<activity android:name=".activities.DemoActivity"
            android:screenOrientation="portrait"
            **android:noHistory="true"**
            />
 1
Author: Sagar Devanga,
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
2015-06-09 07:16:12

En primer lugar, Android no recomienda hacer eso dentro del botón atrás, sino que utiliza los métodos de ciclo de vida proporcionados. El botón atrás no debe destruir la Actividad.

Las actividades se agregan a la pila, accesible desde la Vista general (botón cuadrado desde que introdujeron el Material design en 5.0) cuando se presiona el botón atrás en la última Actividad restante de la pila de interfaz de usuario. Si el usuario quiere cerrar su aplicación, debe deslizar (cerrarla) desde el menú Resumen.

Su aplicación es responsable de detener cualquier tarea y trabajo en segundo plano que no desee ejecutar, en los métodos de ciclo de vida onPause(), onStop() y onDestroy (). Por favor, lea más sobre los ciclos de vida y su correcta implementación aquí: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

Pero para responder a su pregunta, puede hacer hacks para implementar el comportamiento exacto que desea, pero como he dicho, no es recomendado :

@Override
 public void onBackPressed() {

// make sure you have this outcommented
// super.onBackPressed();
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);
}
 1
Author: captainserious,
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
2015-10-01 14:15:41

Para salir de una aplicación de Android, simplemente use. en su Actividad Principal, o puede utilizar el archivo de manifiesto de Android para establecer

android:noHistory="true"
 1
Author: Uday Shah,
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-01-17 04:14:16

Termina tu current_activity usando el método finish() onBack method of your current_activity

Y luego agregue las siguientes líneas en onDestroy de la current_activity para Eliminar Force close

@Override
public void onDestroy()
{
    android.os.Process.killProcess(android.os.Process.myPid());
    super.onDestroy();
}
 0
Author: Naveed Ahmad,
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-11-25 12:48:08

Modificé la respuesta @Vlad_Spays para que el botón atrás actúe normalmente a menos que sea el último elemento de la pila, luego le pregunte al usuario antes de salir de la aplicación.

@Override
public void onBackPressed(){
    if (isTaskRoot()){
        if (backButtonCount >= 1){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }else{
            Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
            backButtonCount++;
        }
    }else{
        super.onBackPressed();
    }
}
 0
Author: seekingStillness,
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-03-08 23:57:22