Finalizar todas las actividades anteriores


Mi aplicación tiene las siguientes pantallas de flujo:

Home->screen 1->screen 2->screen 3->screen 4->screen 5

Ahora tengo un botón común log out en cada pantalla

(Home/ screen 1 / screen 2 /screen 3/ screen 4 / screen 5)

Quiero que cuando el usuario haga clic en el botón cerrar sesión(desde cualquier pantalla), todas las pantallas se terminarán y se abrirá una nueva pantalla Log in.

He intentado casi todos FLAG_ACTIVITY para lograr esto. También voy a través de algunas respuestas en stackoverflow, pero no ser capaz de resolver el problema. Mi aplicación está en Android 1.6 por lo que no ser capaz de usar FLAG_ACTIVITY_CLEAR_TASK

¿hay alguna manera de resolver el problema ?

Author: Adnan Abdollah Zaki, 2011-06-13

24 answers

Uso:

Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Esto borrará todas las actividades en la parte superior de la casa.

Suponiendo que esté terminando la pantalla de inicio de sesión cuando el usuario inicia sesión y se crea home y luego todas las pantallas de 1 a 5 encima de esa. El código que publiqué te devolverá a la pantalla de inicio terminando todas las otras actividades. Puede agregar un extra en la intent y leerlo en la actividad de la pantalla de inicio y terminarlo también (tal vez inicie la pantalla de inicio de sesión nuevamente desde allí o algo).

Yo soy no estoy seguro, pero también puedes intentar iniciar sesión con esta bandera. No se como se ordenaran las actividades en ese caso. Así que no sé si borrará los que están debajo de la pantalla en la que se encuentra, incluyendo el que se encuentra actualmente, pero definitivamente es el camino a seguir.

Espero que esto ayude.

 469
Author: DArkO,
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-26 20:37:53

Puede intentar Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK. Borrará totalmente todas las actividades anteriores y comenzará una nueva actividad.

 268
Author: Kong Ken,
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
2012-11-20 08:08:50

Antes de iniciar su nueva actividad, simplemente agregue el siguiente código:

finishAffinity();

O si quieres que funcione en versiones anteriores de Android:

ActivityCompat.finishAffinity(this);
 108
Author: Henrique,
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-07-29 13:11:05

Cuando el usuario desea salir de todas las actividades abiertas, debe presionar un botón que cargue la primera Actividad que se ejecuta cuando se inicia la aplicación, borrar todas las demás actividades, y luego hacer que finalice la última actividad restante. Haga que se ejecute el siguiente código cuando el usuario presione el botón exit. En mi caso, LoginActivity es la primera actividad en mi programa en ejecutarse.

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

El código anterior borra todas las actividades excepto LoginActivity. A continuación, poner el siguiente código dentro de la LoginActivity ' s onCreate(...), para escuchar cuando se vuelve a crear LoginActivity y se pasa la señal 'EXIT':

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}

¿Por qué es tan difícil hacer un botón de salida en Android?

Android se esfuerza por disuadirte de tener un botón de "salir" en tu aplicación, porque quieren que el usuario nunca se preocupe por si los programas que usa se ejecutan en segundo plano o no.

Los desarrolladores del sistema operativo Android quieren que su programa sea capaz de sobrevivir a un apagado inesperado y apagado de el teléfono, y cuando el usuario reinicia el programa, recoger justo donde lo habían dejado. Para que el usuario pueda recibir una llamada telefónica mientras usa su aplicación y abrir mapas, lo que requiere que su aplicación se libere para obtener más recursos.

Cuando el usuario reanuda su aplicación, continúa justo donde lo dejó sin interrupción. Este botón de salida está usurpando la energía del administrador de actividades, lo que podría causar problemas con la vida del programa Android administrado automáticamente ciclo.

 36
Author: Eric Leschinski,
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
2012-09-08 06:07:51
Intent intent = new Intent(this, classObject);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

Esto funcionará para todas las versiones de Android. Donde IntentCompat la clase agregada en la biblioteca de soporte de Android.

 29
Author: Gem,
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-05-23 08:16:56

Utilice lo siguiente para la actividad

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

Elimine la bandera CLEAR_TASK para usar fragmentos.

Espero que esto pueda ser útil para algunas personas.

 25
Author: Aristo Michael,
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-03-05 10:54:17

De developer.android.com:

public void finishAffinity ()

Añadido en el nivel de API 16

Termina esta actividad así como todas las actividades inmediatamente debajo de ella en la tarea actual que tengan la misma afinidad. Esto se usa normalmente cuando una aplicación se puede iniciar en otra tarea (como desde un ACTION_VIEW de un tipo de contenido que entiende) y el usuario ha utilizado la navegación ascendente para cambiar de la tarea actual a su propia tarea. En este caso, si el usuario tiene navegadas hacia abajo en cualquier otra actividad de la segunda aplicación, todas ellas deben eliminarse de la tarea original como parte del conmutador de tareas.

Tenga en cuenta que este acabado no le permite entregar resultados a la actividad anterior, y se lanzará una excepción si está tratando de hacerlo.

 17
Author: gmrl,
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
2012-11-28 12:25:04

Si tu aplicación tiene como mínimo la versión 16 del sdk, puedes usar finishAffinity()

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

Esto es trabajo para mí En la pantalla de pago superior eliminar todas las actividades de back-stack,

@Override
public void onBackPressed() {
         finishAffinity();
        startActivity(new Intent(PaymentDoneActivity.this,Home.class));
    } 

Http://developer.android.com/reference/android/app/Activity.html#finishAffinity%28%29

 12
Author: Jaydeep purohit,
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-07-03 09:50:17

Una solución que implementé para esto (creo que la encontré en Stack Overflow en algún lugar, pero no recuerdo, así que gracias a quien lo hizo en primer lugar):

De cualquiera de sus actividades haga esto:

// Clear your session, remove preferences, etc.
Intent intent  = new Intent(getBaseContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Luego en tu LoginActivity, sobrescribe onKeyDown:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
 10
Author: Andy,
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
2012-09-08 06:13:56

Para el botón de cierre de sesión en la última pantalla de la aplicación, use este código en el oyente del botón de cierre de sesión para terminar todas las actividades anteriores abiertas, y su problema se resuelve.

{
Intent intent = new Intent(this, loginScreen.class);
ntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
 10
Author: Amrit,
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-11-26 10:44:47
    Intent i1=new Intent(getApplicationContext(),StartUp_Page.class);
i1.setAction(Intent.ACTION_MAIN);
i1.addCategory(Intent.CATEGORY_HOME);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i1);
finish();
 8
Author: Prashant Kumar,
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-12 06:15:08

Tengo el mismo problema puedes usar IntentCompat, así:

import android.support.v4.content.IntentCompat;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);

Este código funciona para mí .

Api de Android 17

 8
Author: Adnan Abdollah Zaki,
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-11-26 19:09:25

En una nota al margen, es bueno saberlo
Esta respuesta funciona ( https://stackoverflow.com/a/13468685/7034327 )

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();

Mientras que esto no funciona

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

.setFlags() reemplaza cualquier indicador anterior y no añade ningún indicador nuevo mientras que .addFlags() lo hace.

Así que esto también funcionará

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
 8
Author: John,
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:26:33

Iniciar sesión - >Inicio - > pantalla 1 - > pantalla 2- > pantalla 3 - > pantalla 4 - > pantalla 5

En la pantalla 4 (o cualquier otra) - >

StartActivity(Log in)
con
FLAG_ACTIVITY_CLEAR_TOP
 6
Author: Plamen Nikolov,
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-03-27 13:33:49

Supongo que llego tarde, pero hay una respuesta simple y corta. Hay un método finishAffinity() en Activity que finalizará la actividad actual y todas las actividades principales, pero solo funciona en Android 4.1 o superior.

Para API 16+, use

finishAffinity();

Para menos de 16, utilizar

ActivityCompat.finishAffinity(YourActivity.this);

Espero que ayude!

 6
Author: Akshay Taru,
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-05-27 08:03:08

Si está usando startActivityForResult() en sus actividades anteriores, simplemente anule OnActivityResult() y llame al método finish(); dentro de él en todas las actividades.. Esto hará el trabajo...

 5
Author: ngesh,
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
2012-09-08 06:02:44

Para API > = 15 a API 23 solución simple.

 Intent nextScreen = new Intent(currentActivity.this, MainActivity.class);
 nextScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
 startActivity(nextScreen);
 ActivityCompat.finishAffinity(currentActivity.this);
 5
Author: lotus weaver,
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-11-04 17:52:23

En lugar de usar finish() solo use finishAffinity();

 5
Author: Hitesh Kushwah,
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-05-19 06:00:45

Cuando el usuario haga clic en el botón cerrar sesión, escriba el siguiente código:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Y también cuando después de iniciar sesión si llama a una nueva actividad no use finish ();

 3
Author: nikki,
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
2012-08-07 12:43:01

En el nivel de API 11 o superior, use FLAG_ACTIVITY_CLEAR_TASK y FLAG_ACTIVITY_NEW_TASK flag en Intent para borrar toda la pila de actividad.

Intent i = new Intent(OldActivity.this, NewActivity.class);
// set the new task and clear flags
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i);
 3
Author: Krishna Mohan 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
2018-07-03 03:38:06

Si inicia sesión en el usuario en screen 1 y desde allí va a las otras pantallas, use

Intent intent = new Intent(this, Screen1.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
 1
Author: Gabriel Negut,
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
2011-06-13 12:23:36

Simplemente, cuando vaya desde la pantalla de inicio de sesión, no cuando termine la pantalla de inicio de sesión.

Y luego en todas las actividades forward, use esto para cerrar sesión:

final Intent intent = new Intent(getBaseContext(), LoginScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);

Funciona perfectamente.

 1
Author: Asad Rao,
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
2012-09-08 06:14:54

Encontré esta manera, borrará toda la historia y saldrá

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
Intent intent = new Intent(getApplicationContext(), SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

finish();
System.exit(0);
 1
Author: piero.ir,
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-10 19:16:40

Encontré que esta solución funciona en todos los dispositivos a pesar del nivel de API (incluso para

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
startActivity(mainIntent);
 0
Author: priyankvex,
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-06-05 08:22:56