Recargar actividad en Android


¿Es una buena práctica recargar un Activity en Android?

¿Cuál sería la mejor manera de hacerlo? this.finish y luego this.startActivity con la actividad Intent?

Author: N J, 2010-06-16

14 answers

Simplemente puede usar

finish();
startActivity(getIntent());

Para refrescar un Activity desde dentro.

 412
Author: Sush,
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-26 18:24:43

Esto es lo que hago para recargar la actividad después de cambiar al regresar de un cambio de preferencia.

@Override
protected void onResume() {

   super.onResume();
   this.onCreate(null);
}

Esto esencialmente hace que la actividad se redibuje a sí misma.

Actualizado: Una mejor manera de hacer esto es llamar al método recreate(). Esto hará que la actividad sea recreada.

 28
Author: kingargyle,
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-08-12 22:31:48

Para aquellos que no quieren ver ese parpadeo después del método recreate () simplemente use

 finish();
 overridePendingTransition(0, 0);
 startActivity(getIntent());
 overridePendingTransition(0, 0);
 23
Author: AMAN 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
2017-01-11 11:00:37

Necesitaba actualizar una lista de mensajes en una de mis aplicaciones a toda prisa, así que solo realicé una actualización de mi actividad principal de la interfaz de usuario antes de cerrar el cuadro de diálogo en el que estaba. Estoy seguro de que hay mejores maneras de lograr esto.

// Refresh main activity upon close of dialog box
Intent refresh = new Intent(this, clsMainUIActivity.class);
startActivity(refresh);
this.finish(); //
 10
Author: ninehundredt,
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-10-09 12:11:32

Android incluye un sistema de gestión de procesos que maneja la creación y destrucción de actividades que en gran medida niega cualquier beneficio que vería al reiniciar manualmente una actividad. Puede ver más información al respecto en Fundamentos de la aplicación

Sin embargo, lo que es una buena práctica es asegurarse de que sus métodos onPause y onStop liberen cualquier recurso al que no necesite aferrarse y use onLowMemory para reducir sus necesidades de actividades a la absoluta mínimo.

 9
Author: Al Sutton,
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-10-09 09:58:22

Comienza con una intent tu misma activity y cierra la activity.

Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.
 5
Author: Jorgesys,
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-10-09 22:12:36

Tengo el mismo problema

import android.support.v4.content.IntentCompat;

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);

Este código funciona para mí . Android api 17

 2
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-03-05 11:57:06

En algunos casos es la mejor práctica en otros no es una buena idea es impulsado por el contexto si eliges hacerlo usando lo siguiente es la mejor manera de pasar de una actividad a sus hijos :

    Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);    
    startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);

La cosa es que cada vez que terminas () de activityIWishToRun vuelves a tu actividad viviente

 2
Author: yoav.str,
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-11-05 14:44:32

Vi respuestas anteriores que se han dado para recargar la actividad usando Intent. Estos funcionarán, pero también puedes hacer lo mismo usando el método recreate() dado en la propia clase de actividad.

En lugar de escribir esto

/ / Actualizar la actividad principal al cerrar el cuadro de diálogo

Intent refresh = new Intent(this, clsMainUIActivity.class);
startActivity(refresh);
this.finish();

Esto se puede hacer escribiendo esto solo

recreate();
 2
Author: Rizwan,
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-12-26 07:41:07

No creo que sea una buena idea... sería mejor implementar un método más limpio. Por ejemplo, si tu actividad contiene un formulario, el método cleaner podría borrar cada widget del formulario y eliminar todos los datos temporales. Supongo que eso es lo que quieres: restaurar la actividad a su estado inicial.

 1
Author: Cristian,
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-06-16 13:45:18

Después de experimentar con esto durante un tiempo, no he encontrado consecuencias inesperadas de reiniciar una actividad. Además, creo que esto es muy similar a lo que hace Android por defecto cuando la orientación cambia, por lo que no veo una razón para no hacerlo en una circunstancia similar.

 1
Author: hpique,
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-08-06 14:53:34

Tuve otro enfoque como: establecer el launchMode de mi actividad a singleTop y sin llamar a finish(), solo startActivity(getIntent()) hará el trabajo. Solo hay que preocuparse por los nuevos datos tanto en onCreate() y onNewIntent. A la manera de Sush, la aplicación puede parpadear como dijo AMAN SINGH. Pero el enfoque de AMAN SINGH todavía creará una nueva actividad que de alguna manera es innecesaria, incluso si arregló el problema del 'parpadeo', creo.

Demasiado tarde para esta pregunta, pero si alguien busca una solución, aquí está.

 0
Author: WALKER,
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-24 11:42:26

Simplemente use

this.recreate();

Esto activará el método onCreate en la actividad

 0
Author: Yasiru Nayanajith,
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-08-06 16:27:30

En una actividad puedes llamar a recreate() para" recrear " la actividad (API 11+)

 -1
Author: ,
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-08-10 07:22:28