Cómo salir de la aplicación y mostrar la pantalla de inicio?


Tengo una aplicación donde en la página de inicio tengo botones para la navegación a través de la aplicación.

En esa página tengo un botón "EXIT" que al hacer clic debe llevar al usuario a la pantalla de inicio en el teléfono donde está el icono de la aplicación.

¿Cómo puedo hacer eso?

18 answers

El diseño de Android no favorece la salida de una aplicación por elección, sino que la gestiona el sistema operativo. Puede abrir la aplicación Home por su Intención correspondiente:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
 312
Author: ognian,
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-03-11 06:26:24

Puede ser que usted puede intentar algo como esto

Supongamos que en nuestra aplicación, tenemos un número de actividades(digamos diez) y necesitamos salir directamente de esta actividad. Lo que podemos hacer es crear una intent e ir a la actividad raíz y establecer flag en la intent como

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

También, añade algo extra como booleano a la intent

intent.putExtra("EXIT", true);

Luego en la actividad raíz, verifique el valor de boolean y de acuerdo con esa llamada finish(), en el onCreate() de la actividad raíz

if (getIntent().getBooleanExtra("EXIT", false)) {
 finish();
}
 71
Author: Kartik Domadiya,
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-03-16 10:23:39
System.exit(0);

Es probablemente lo que estás buscando. Cerrará toda la aplicación y lo llevará a la pantalla de inicio.

 27
Author: Ndupza,
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-07-31 10:05:53

Esto funciona bien para mí.
Cierre todas las actividades anteriores de la siguiente manera:

    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("Exit me", true);
    startActivity(intent);
    finish();

Luego en el método MainActivity onCreate() agregue esto para finalizar la MainActivity

    setContentView(R.layout.main_layout);

    if( getIntent().getBooleanExtra("Exit me", false)){
        finish();
        return; // add this to prevent from doing unnecessary stuffs
    }
 24
Author: Lazy Ninja,
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-04-11 00:57:32

Primero termina tu solicitud usando el método finish();

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

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
 22
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
2012-11-05 14:06:47

Si desea finalizar una actividad, simplemente puede llamar a finish(). Sin embargo, es una mala práctica tener un botón de salida en la pantalla.

 19
Author: Christian,
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-03-31 08:49:03

No se recomienda salir de su aplicación Android. Vea esta pregunta para más detalles.

El usuario siempre puede salir de su aplicación a través del botón de inicio o en la primera actividad a través del botón atrás.

 16
Author: Janusz,
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 11:55:19

Algunas Actividades en realidad no desea abrir de nuevo cuando se presiona el botón atrás, como la Actividad de la Pantalla de Bienvenida, la Actividad de la Pantalla de Bienvenida, las Ventanas de Confirmación. En realidad no necesitas esto en la pila de actividad. puedes hacer esto usando= > open manifest.archivo xml y añadir un atributo

Android: noHistory = "true"

A estas actividades.

<activity
    android:name="com.example.shoppingapp.AddNewItems"
    android:label="" 
    android:noHistory="true">
</activity>

O

A veces desea cerrar toda la aplicación en cierta pulsación del botón atrás. Aquí las mejores prácticas están abiertas la ventana de inicio en lugar de salir de la aplicación. Para eso necesitas sobrescribir el método onBackPressed (). por lo general, este método abre la actividad superior en la pila.

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

}

O

En el botón atrás presionado desea salir de esa actividad y también tampoco desea agregar esto en la pila de actividad. llama al método finish() dentro del método onBackPressed (). no hará cerrar toda la aplicación. irá para la actividad anterior en la pila.

@Override
public void onBackPressed() {
  finish();
}
 16
Author: Burusothman,
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-04-21 06:50:12

(Probé respuestas anteriores pero carecen en algunos puntos. Por ejemplo, si no realiza un return; después de finalizar la actividad, se ejecuta el código de actividad restante. También es necesario editar onCreate con retorno. Si no funciona super.onCreate () obtendrá un error de tiempo de ejecución)

Digamos que tienes MainActivity y ChildActivity.

Dentro de ChildActivity agregue esto:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;

Dentro del onCreate de MainActivity agregue esto:

@Override
public void onCreate(Bundle savedInstanceState) {

    mContext = getApplicationContext();

    super.onCreate(savedInstanceState);

    if (getIntent().getBooleanExtra("EXIT", false)) {
        finish();
        return;
    }
    // your current codes
    // your current codes
}
 5
Author: trante,
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-01-16 22:40:21

Hay otra opción, usar el método FinishAffinity para cerrar todas las tareas de la pila relacionadas con la aplicación.

Véase: https://stackoverflow.com/a/27765687/1984636

 4
Author: sivi,
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 11:33:15

Cuando u call finish onDestroy() de esa actividad será llamada y volverá a la actividad anterior en la pila de actividad... Tan.. para exit no llame a finish ();

 3
Author: Isham,
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-03-08 05:09:02

Esto es lo que hice:

Algo de actividad.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Básicamente lo que hiciste es borrar todas las actividades de la pila y lanzar QuitAppActivity, que terminará la tarea.

 3
Author: Irshu,
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-02 04:32:10

Añadir las siguientes líneas después de finish(); en onDestroy():

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
 0
Author: Ramanathan,
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-12-31 17:44:26

Intenté salir de la aplicación usando el siguiente fragmento de código, esto funcionó para mí. Espero que esto te ayude. hice una pequeña demostración con 2 actividades

Primera actividad

public class MainActivity extends Activity implements OnClickListener{
    private Button secondActivityBtn;
    private SharedPreferences pref;
    private SharedPreferences.Editor editer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        secondActivityBtn=(Button) findViewById(R.id.SecondActivityBtn);
        secondActivityBtn.setOnClickListener(this);

        pref = this.getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
        editer = pref.edit();

        if(pref.getInt("exitApp", 0) == 1){
            editer.putInt("exitApp", 0);
            editer.commit();
            finish();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.SecondActivityBtn:
            Intent intent= new Intent(MainActivity.this, YourAnyActivity.class);
            startActivity(intent);
            break;
        default:
            break;
        }
    }
}

Su cualquier otra actividad

public class YourAnyActivity extends Activity implements OnClickListener {
    private Button exitAppBtn;
    private SharedPreferences pref;
    private SharedPreferences.Editor editer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_any);

        exitAppBtn = (Button) findViewById(R.id.exitAppBtn);
        exitAppBtn.setOnClickListener(this);

        pref = this.getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
        editer = pref.edit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.exitAppBtn:
            Intent main_intent = new Intent(YourAnyActivity.this,
                    MainActivity.class);
            main_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(main_intent);
            editer.putInt("exitApp",1);
            editer.commit();
            break;
        default:
            break;
        }
    }
}
 0
Author: Amol Sawant 96 Kuli,
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-26 17:32:05

Lo hice en modo observador.

Interfaz de observador

public interface Observer {
public void update(Subject subject);
}

Sujeto base

public class Subject {
private List<Observer> observers = new ArrayList<Observer>();

public void attach(Observer observer){
    observers.add(observer);
}

public void detach(Observer observer){
    observers.remove(observer);
}

protected void notifyObservers(){
    for(Observer observer : observers){
        observer.update(this);
    }
}
}

El sujeto hijo implementa el método exit

public class ApplicationSubject extends Subject {
public void exit(){
    notifyObservers();
}
}

MiAplicación que su solicitud debe extenderla

public class MyApplication extends Application {

private static ApplicationSubject applicationSubject;

public ApplicationSubject getApplicationSubject() {
            if(applicationSubject == null) applicationSubject = new ApplicationSubject();
    return applicationSubject;
}

}

Actividad de base

public abstract class BaseActivity extends Activity implements Observer {

public MyApplication app;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    app = (MyApplication) this.getApplication();
    app.getApplicationSubject().attach(this);
}

@Override
public void finish() {
    // TODO Auto-generated method stub
            app.getApplicationSubject().detach(this);
    super.finish();
}

/**
 * exit the app
 */
public void close() {
    app.getApplicationSubject().exit();
};

@Override
public void update(Subject subject) {
    // TODO Auto-generated method stub
    this.finish();
}

}

Vamos a probarlo

public class ATestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    close(); //invoke 'close'
}
}
 0
Author: Hunter,
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-05-02 07:44:19

Si desea salir de la aplicación ponga este código bajo su función

public void yourFunction()
{
finishAffinity();   
moveTaskToBack(true);

}



//For an instance, if you want to exit an application on double click of a 
//button,then the following code can be used.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 2) {
        // do something on back.
        From Android 16+ you can use the following:

        finishAffinity();
        moveTaskToBack(true);
    }

    return super.onKeyDown(keyCode, event);
}
 0
Author: Dila Gurung,
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-26 19:29:25

100% funciona bien. este es el código para Salir de su aplicación onClick (Método)

    Button exit = (Button)findViewById(R.id.exitbutton);

    exit.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            finish();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
            Toast.makeText(getApplicationContext(), "Closed Completely and Safely", Toast.LENGTH_LONG).show();

        }
    });
 0
Author: Vivek Akkaldevi,
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-06-19 12:54:54

Si desea salir de su aplicación. A continuación, utilice este código dentro de su evento pulsado botón. como:

public void onBackPressed()
{
    moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(1);
}
 -2
Author: Pir Fahim 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
2015-09-14 18:36:32