Come chiudere l'applicazione Android?


157

Voglio chiudere la mia applicazione, in modo che non venga più eseguita in background.

Come farlo? Questa buona pratica è su piattaforma Android?

Se faccio affidamento sul pulsante "indietro", si chiude l'app, ma rimane in background. Esiste persino un'applicazione chiamata "TaskKiller" solo per uccidere quelle app in background.



ti chiedi perché non vorrebbe che la sua app funzionasse anche in background?
Darpan,

Risposte:


139

Android ha un meccanismo in atto per chiudere un'applicazione in modo sicuro secondo la sua documentazione. Nell'ultima attività che è uscita (di solito l'attività principale che è venuta per la prima volta all'avvio dell'applicazione) basta posizionare un paio di righe nel metodo onDestroy (). La chiamata a System.runFinalizersOnExit (true) garantisce che tutti gli oggetti vengano finalizzati e che la spazzatura venga raccolta alla chiusura dell'applicazione. Puoi anche uccidere rapidamente un'applicazione tramite android.os.Process.killProcess (android.os.Process.myPid ()) se preferisci. Il modo migliore per farlo è inserire un metodo come il seguente in una classe di supporto e quindi chiamarlo ogni volta che l'app deve essere uccisa. Ad esempio nel metodo di distruzione dell'attività radice (supponendo che l'app non uccida mai questa attività):

Inoltre Android non notificherà un'applicazione dell'evento del tasto HOME , quindi non è possibile chiudere l'applicazione quando si preme il tasto HOME . Android si riserva l' evento chiave HOME in modo che uno sviluppatore non possa impedire agli utenti di abbandonare la propria applicazione. Tuttavia è possibile determinare con il tasto HOME premuto premendo un flag su true in una classe helper che presuppone che il tasto HOME sia stato premuto, quindi cambiando il flag in false quando si verifica un evento che mostra che il tasto HOME non è stato premuto e quindi controllando di vedere il tasto HOME premuto nel metodo onStop () dell'attività.

Non dimenticare di gestire il tasto HOME per qualsiasi menu e nelle attività avviate dai menu. Lo stesso vale per il tasto CERCA . Di seguito sono riportate alcune classi di esempio da illustrare:

Ecco un esempio di un'attività di root che uccide l'applicazione quando viene distrutta:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 */

public class HomeKey extends CustomActivity {

    public void onDestroy() {
        super.onDestroy();

        /*
         * Kill application when the root activity is killed.
         */
        UIHelper.killApp(true);
    }

}

Ecco un'attività astratta che può essere estesa per gestire il tasto HOME per tutte le attività che lo estendono:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 */

import android.app.Activity;
import android.view.Menu;
import android.view.MenuInflater;

/**
 * Activity that includes custom behavior shared across the application. For
 * example, bringing up a menu with the settings icon when the menu button is
 * pressed by the user and then starting the settings activity when the user
 * clicks on the settings icon.
 */
public abstract class CustomActivity extends Activity {
    public void onStart() {
        super.onStart();

        /*
         * Check if the app was just launched. If the app was just launched then
         * assume that the HOME key will be pressed next unless a navigation
         * event by the user or the app occurs. Otherwise the user or the app
         * navigated to this activity so the HOME key was not pressed.
         */

        UIHelper.checkJustLaunced();
    }

    public void finish() {
        /*
         * This can only invoked by the user or the app finishing the activity
         * by navigating from the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
        super.finish();
    }

    public void onStop() {
        super.onStop();

        /*
         * Check if the HOME key was pressed. If the HOME key was pressed then
         * the app will be killed. Otherwise the user or the app is navigating
         * away from this activity so assume that the HOME key will be pressed
         * next unless a navigation event by the user or the app occurs.
         */
        UIHelper.checkHomeKeyPressed(true);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.settings_menu, menu);

        /*
         * Assume that the HOME key will be pressed next unless a navigation
         * event by the user or the app occurs.
         */
        UIHelper.homeKeyPressed = true;

        return true;
    }

    public boolean onSearchRequested() {
        /*
         * Disable the SEARCH key.
         */
        return false;
    }
}

Ecco un esempio di una schermata del menu che gestisce il tasto HOME :

/**
 * @author Danny Remington - MacroSolve
 */

package android.example;

import android.os.Bundle;
import android.preference.PreferenceActivity;

/**
 * PreferenceActivity for the settings screen.
 * 
 * @see PreferenceActivity
 * 
 */
public class SettingsScreen extends PreferenceActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.settings_screen);
    }

    public void onStart() {
        super.onStart();

        /*
         * This can only invoked by the user or the app starting the activity by
         * navigating to the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
    }

    public void finish() {
        /*
         * This can only invoked by the user or the app finishing the activity
         * by navigating from the activity so the HOME key was not pressed.
         */
        UIHelper.homeKeyPressed = false;
        super.finish();
    }

    public void onStop() {
        super.onStop();

        /*
         * Check if the HOME key was pressed. If the HOME key was pressed then
         * the app will be killed either safely or quickly. Otherwise the user
         * or the app is navigating away from the activity so assume that the
         * HOME key will be pressed next unless a navigation event by the user
         * or the app occurs.
         */
        UIHelper.checkHomeKeyPressed(true);
    }

    public boolean onSearchRequested() {
        /*
         * Disable the SEARCH key.
         */
        return false;
    }

}

Ecco un esempio di una classe di supporto che gestisce la chiave HOME in tutta l'app:

package android.example;

/**
 * @author Danny Remington - MacroSolve
 *
 */

/**
 * Helper class to help handling of UI.
 */
public class UIHelper {
    public static boolean homeKeyPressed;
    private static boolean justLaunched = true;

    /**
     * Check if the app was just launched. If the app was just launched then
     * assume that the HOME key will be pressed next unless a navigation event
     * by the user or the app occurs. Otherwise the user or the app navigated to
     * the activity so the HOME key was not pressed.
     */
    public static void checkJustLaunced() {
        if (justLaunched) {
            homeKeyPressed = true;
            justLaunched = false;
        } else {
            homeKeyPressed = false;
        }
    }

    /**
     * Check if the HOME key was pressed. If the HOME key was pressed then the
     * app will be killed either safely or quickly. Otherwise the user or the
     * app is navigating away from the activity so assume that the HOME key will
     * be pressed next unless a navigation event by the user or the app occurs.
     * 
     * @param killSafely
     *            Primitive boolean which indicates whether the app should be
     *            killed safely or quickly when the HOME key is pressed.
     * 
     * @see {@link UIHelper.killApp}
     */
    public static void checkHomeKeyPressed(boolean killSafely) {
        if (homeKeyPressed) {
            killApp(true);
        } else {
            homeKeyPressed = true;
        }
    }

    /**
     * Kill the app either safely or quickly. The app is killed safely by
     * killing the virtual machine that the app runs in after finalizing all
     * {@link Object}s created by the app. The app is killed quickly by abruptly
     * killing the process that the virtual machine that runs the app runs in
     * without finalizing all {@link Object}s created by the app. Whether the
     * app is killed safely or quickly the app will be completely created as a
     * new app in a new virtual machine running in a new process if the user
     * starts the app again.
     * 
     * <P>
     * <B>NOTE:</B> The app will not be killed until all of its threads have
     * closed if it is killed safely.
     * </P>
     * 
     * <P>
     * <B>NOTE:</B> All threads running under the process will be abruptly
     * killed when the app is killed quickly. This can lead to various issues
     * related to threading. For example, if one of those threads was making
     * multiple related changes to the database, then it may have committed some
     * of those changes but not all of those changes when it was abruptly
     * killed.
     * </P>
     * 
     * @param killSafely
     *            Primitive boolean which indicates whether the app should be
     *            killed safely or quickly. If true then the app will be killed
     *            safely. Otherwise it will be killed quickly.
     */
    public static void killApp(boolean killSafely) {
        if (killSafely) {
            /*
             * Notify the system to finalize and collect all objects of the app
             * on exit so that the virtual machine running the app can be killed
             * by the system without causing issues. NOTE: If this is set to
             * true then the virtual machine will not be killed until all of its
             * threads have closed.
             */
            System.runFinalizersOnExit(true);

            /*
             * Force the system to close the app down completely instead of
             * retaining it in the background. The virtual machine that runs the
             * app will be killed. The app will be completely created as a new
             * app in a new virtual machine running in a new process if the user
             * starts the app again.
             */
            System.exit(0);
        } else {
            /*
             * Alternatively the process that runs the virtual machine could be
             * abruptly killed. This is the quickest way to remove the app from
             * the device but it could cause problems since resources will not
             * be finalized first. For example, all threads running under the
             * process will be abruptly killed when the process is abruptly
             * killed. If one of those threads was making multiple related
             * changes to the database, then it may have committed some of those
             * changes but not all of those changes when it was abruptly killed.
             */
            android.os.Process.killProcess(android.os.Process.myPid());
        }

    }
}

1
Questo dovrebbe uccidere l'intera applicazione che ha chiamato System.exit (0) incluse tutte le attività che sono in esecuzione come parte dell'applicazione. Tutte le altre applicazioni continueranno a funzionare. Se vuoi uccidere solo un'attività nell'applicazione ma non tutte le attività nell'applicazione, devi chiamare il metodo finish () dell'attività che vuoi uccidere.
Danny Remington - OMS,

2
Grazie mille per questo nfo. Sto realizzando un gioco con AndEngine e quando chiamerei finish, anche in tutte le attività, Android non si sarebbe ancora ripulito completamente e quando il gioco sarebbe stato rilanciato, sarebbe stato completamente infastidito, le mie trame GL sarebbero state tutte eliminate, ecc. Quindi, dopo aver indagato, pensando che fosse AndEngine, mi sono reso conto che doveva essere qualcosa che andava storto perché Android stava cercando di preservare il processo quando desideravo uscire. Tutti i commenti "oh, non dovresti chiamare exit, rovina l'esperienza dell'utente" non ha senso. Meteo un'applicazione dovrebbe rimanere aperta .......

17
Nessuna applicazione di produzione dovrebbe utilizzare questo codice. Nessuna applicazione di produzione dovrebbe chiamare uno dei codici indicati killApp(), poiché Google ha indicato che porterà a comportamenti imprevedibili.
CommonsWare,

1
System.runFinalizersOnExit (true); Il metodo è obsoleto. Qual è un altro modo per chiudere un'applicazione in modo sicuro (immondizia raccolta) ?.
Ajeesh,

1
Non è stato deprecato al momento della pubblicazione originale. Poiché l'AP corrente era quindi 7 e l'API corrente ora è 19, probabilmente c'è un altro modo per farlo ora.
Danny Remington - OMS

68

SÌ! Puoi sicuramente chiudere la tua applicazione in modo che non sia più in esecuzione in background. Come altri hanno commentato, finish()il modo consigliato da Google non significa che il tuo programma sia chiuso.

System.exit(0);

Proprio lì chiuderai la tua applicazione lasciando nulla in esecuzione in background.Tuttavia, usalo con saggezza e non lasciare i file aperti, gli handle di database aperti, ecc. Queste cose verrebbero normalmente ripulite tramite il finish()comando.

Personalmente odio quando scelgo Exit in un'applicazione e non esce.


44
L'uso di System.exit () non è assolutamente raccomandato.
Commons War

14
Non sosterrò che non è il modo consigliato ma puoi fornire una soluzione che garantisca che l'applicazione venga immediatamente abbandonata dallo sfondo? In caso contrario, System.exit è la strada da percorrere fino a quando Google non fornirà un metodo migliore.
Cameron McBride,

74
Chi decide che non sei "supposto", le stesse persone che hanno creato un metodo che in realtà non esce? Se gli utenti non volessero chiudere le loro applicazioni, la quinta app a pagamento più popolare non sarebbe un killer di attività. Le persone hanno bisogno di liberare memoria e il sistema operativo principale non fa il lavoro.
Cameron McBride,

19
Concordato sul fatto che è sconsiderato, ma votato per aver fornito una risposta effettiva alla domanda posta. Mi sto molto stancando di sentire "non vuoi davvero farlo", senza spiegazioni di follow-up. Android è un incubo assoluto per quanto riguarda la documentazione per questo tipo di cose rispetto a iPhone.
DougW,

11
Non vi è alcun vantaggio in termini di memoria nell'utilizzo di Task Killer con Android. Android distruggerà e pulirà tutte le applicazioni che non sono in primo piano se l'app in primo piano necessita di più memoria. In alcuni casi Android riapre persino un'app che è stata chiusa con il task killer. Android riempirà tutta la memoria non necessaria con le applicazioni utilizzate di recente per ridurre il tempo di commutazione dell'app. NON COSTRUIRE LE APP CON UN PULSANTE DI USCITA. NON UTILIZZARE UN GESTORE DI ATTIVITÀ SU ANDROID. geekfor.me/faq/you-shouldnt-be-using-a-task-killer-with-android android-developers.blogspot.com/2010/04/…
Janusz

23

Questo è il modo in cui l'ho fatto:

Ho appena messo

Intent intent = new Intent(Main.this, SOMECLASSNAME.class);
Main.this.startActivityForResult(intent, 0);

all'interno del metodo che apre un'attività, quindi all'interno del metodo di SOMECLASSNAME progettato per chiudere l'app che ho inserito:

setResult(0);
finish();

E ho inserito quanto segue nella mia classe principale:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode == 0) {
        finish();
    }
}

18

Solo per rispondere alla mia domanda ora dopo così tanto tempo (dal momento che CommonsWare ha commentato la risposta più popolare dicendo che NON dovremmo farlo):

Quando voglio uscire dall'app:

  1. Inizio la mia prima attività (schermata iniziale o qualsiasi altra attività sia attualmente nella parte inferiore dello stack di attività) con FLAG_ACTIVITY_CLEAR_TOP(che chiuderà tutte le altre attività avviate dopo di essa, il che significa - tutte). Basta fare in modo che questa attività sia nello stack di attività (non finirla per qualche motivo in anticipo).
  2. Invito finish()questa attività

Questo è tutto, funziona abbastanza bene per me.


3
Questo in realtà non uccide la tua app. Verrà comunque visualizzato nell'elenco delle app. Uccido solo tutte le tue attività.
Joris Weimar,

1
FLAG_ACTIVITY_CLEAN_TOP non funziona con gli smartphone Sony. Puoi aggirare il problema aggiungendo android: clearTaskOnLaunch = "true" attributo all'attività su AndroidManifest.xml
Rusfearuth

10

Basta scrivere questo codice sul pulsante ESCI clic.

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

E nel metodo onCreate () di MainActivity.class scrivi sotto il codice come prima riga,

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

9

Non è possibile utilizzare le API del framework. È a discrezione del sistema operativo (Android) decidere quando rimuovere o conservare un processo in memoria. Questo per motivi di efficienza: se l'utente decide di riavviare l'app, allora è già lì senza che debba essere caricato in memoria.

Quindi no, non è solo scoraggiato , è impossibile farlo.


4
Puoi sempre fare qualcosa come Integer z = null; z.intValue (); // risposta peggiore
Joe Plante,

6
Vero che. Potresti anche sbattere il telefono contro il muro, che terminerà tutte le applicazioni aperte se viene applicata una pressione sufficiente. Non lo consiglierei ancora. Ho aggiornato il mio post di conseguenza.
Matthias,

@JoePlante che lascia anche l'app in background quando si apre il menu delle app. Sembra impossibile.
peresisUser

8

Per uscire dalle modalità app:

Modo 1:

chiama finish();e ignora onDestroy();. Inserisci il seguente codice in onDestroy():

System.runFinalizersOnExit(true)

o

android.os.Process.killProcess(android.os.Process.myPid());

Modo 2:

public void quit() {
    int pid = android.os.Process.myPid();
    android.os.Process.killProcess(pid);
    System.exit(0);
}

Modo 3:

Quit();

protected void Quit() {
    super.finish();
}

Modo 4:

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

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

Modo 5:

A volte la chiamata finish()esce solo dall'attività corrente, non dall'intera applicazione. Tuttavia, esiste una soluzione alternativa per questo. Ogni volta che si avvia un activity, avviarlo usando startActivityForResult(). Quando vuoi chiudere l'intera app, puoi fare qualcosa del tipo:

setResult(RESULT_CLOSE_ALL);
finish();

Quindi definire il onActivityResult(...)callback di ogni attività, quindi quando activityritorna con il RESULT_CLOSE_ALLvalore, chiama anche finish():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(resultCode){
        case RESULT_CLOSE_ALL:{
            setResult(RESULT_CLOSE_ALL);
            finish();
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

Intent intent = new Intent (getApplicationContext (), LoginActivity.class); intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra ("EXIT", true); startActivity (intento); sta funzionando benissimo.
hitesh141,

Ho iniziato l'attività A-> B-> C-> D. Quando si preme il pulsante Indietro su Attività DI, si desidera andare all'attività A. Poiché A è il mio punto di partenza e quindi già in pila tutte le attività in cima ad A vengono cancellate e non è possibile tornare a nessun'altra attività da A . @Override onKeyDown pubblico booleano (int keyCode, evento KeyEvent) {if (keyCode == KeyEvent.KEYCODE_BACK) {Intent a = new Intent (this, A.class); a.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity (a); ritorno vero; } return super.onKeyDown (keyCode, evento); }
hitesh141,

5

Ecco come Windows Mobile ha funzionato per ... beh ... sempre! Ecco cosa Microsoft ha da dire sull'argomento:

http://blogs.msdn.com/windowsmobile/archive/2006/10/05/The-Emperor-Has-No-Close.aspx (è triste che mi sia ricordato il titolo del post sul blog dal 2006? Ho trovato l'articolo su Google cercando "l'imperatore non ha vicino" lol)

In breve:

Se il sistema ha bisogno di più memoria mentre l'app è in background, chiuderà l'app. Ma se il sistema non ha bisogno di più memoria, l'app rimarrà nella RAM e sarà pronta per tornare rapidamente la prossima volta che l'utente ne avrà bisogno.

Molti commenti in questa domanda a O'Reilly suggeriscono che Android si comporta allo stesso modo, chiudendo le applicazioni che non sono state utilizzate per un po 'solo quando Android ha bisogno della memoria che stanno utilizzando.

Dal momento che questa è una funzionalità standard, quindi cambiare il comportamento per chiudere forzatamente significherebbe cambiare l'esperienza dell'utente. Molti utenti sarebbero abituati al delicato licenziamento delle loro app Android, quindi quando ne respingono uno con l'intenzione di tornarci dopo aver eseguito alcune altre attività, potrebbero essere piuttosto frustrati dal fatto che lo stato dell'applicazione venga ripristinato o che impieghi più tempo aprire. Seguirò il comportamento standard perché è quello che ci si aspetta.


5

Chiamando il finish()metodo su un'attività ha l'effetto desiderato su quella attività corrente.


14
No non lo fa. Termina l'attività corrente, non l'applicazione. Se finisci () l'attività più in basso nello stack di attività, la tua applicazione sembrerà uscire, ma Android potrebbe decidere di tenerlo effettivamente attivo per tutto il tempo che ritiene opportuno.
Matthias,

In effetti, tuttavia, se è necessario uscire completamente dall'applicazione, è necessario chiamare il metodo di finitura per ogni attività e pensare anche a tutti i servizi che è possibile aver avviato. Ho anche modificato la risposta iniziale - scusate l'omissione.
r1k0,

3

nessuna delle risposte precedenti funziona bene sulla mia app

ecco il mio codice di lavoro

sul pulsante di uscita:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = IntentCompat.makeRestartActivityTask(cn);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
mainIntent.putExtra("close", true);
startActivity(mainIntent);
finish();

quel codice è quello di chiudere qualsiasi altra attività e portare MainActivity in cima ora su MainActivity:

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

2

Metti una finish();dichiarazione come di seguito:

myIntent.putExtra("key1", editText2.getText().toString());

finish();

LoginActivity.this.startActivity(myIntent);

In ogni attività.


2
@Override
    protected void onPause() {

        super.onPause();

        System.exit(0);

    }

2

Copia il codice seguente e incolla il file AndroidManifest.xml in Primo tag attività.

<activity                        
            android:name="com.SplashActivity"
            android:clearTaskOnLaunch="true" 
            android:launchMode="singleTask"
            android:excludeFromRecents="true">              
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER"
                />
            </intent-filter>
        </activity>     

Aggiungi anche questo codice di seguito in tutto in Tag attività nel file AndroidManifest.xml

 android:finishOnTaskLaunch="true"

1

Non possibile con 2.3. Cerco molte cose e ho provato molte app. La soluzione migliore è installare sia (go taskmanager) che (riavvio veloce). Quando li usi insieme funzionerà e libererà la memoria. Un'altra opzione è l'aggiornamento a Android Ice Cream Sandwich 4.0.4 che consente il controllo (chiusura) delle app.



1

L'uso di finishAffinity()può essere una buona opzione se desideri chiudere tutte le attività dell'app. Secondo i documenti Android-

Finish this activity as well as all activities immediately below it in the current task that have the same affinity.

1
public class CloseAppActivity extends AppCompatActivity
{
    public static final void closeApp(Activity activity)
    {
        Intent intent = new Intent(activity, CloseAppActivity.class);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }

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

e in manifest:

<activity
     android:name=".presenter.activity.CloseAppActivity"
     android:noHistory="true"
     android:clearTaskOnLaunch="true"/>

Quindi è possibile chiamare CloseAppActivity.closeApp(fromActivity)e l'applicazione verrà chiusa.


1

Scrivi semplicemente il seguente codice su onBackPressed:

@Override
public void onBackPressed() {
    // super.onBackPressed();

    //Creating an alert dialog to logout
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Do you want to Exit?");
    alertDialogBuilder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }
            });

    alertDialogBuilder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                }
            });

    //Showing the alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

0

chiamando finish (); nel pulsante OnClick o nel menu

case R.id.menu_settings:

      finish();
     return true;

Come indicato nei commenti di altre risposte, finish()non uccide l'app. Potrebbe tornare all'intento precedente o in background l'App.
Raptor

0

Penso che chiuderà la tua attività e tutte le attività secondarie ad essa correlate.

public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();]
        if (id == R.id.Exit) {
            this.finishAffinity();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

0

Il modo migliore e più breve per utilizzare la tabella System.exit.

System.exit(0);

La VM interrompe l'ulteriore esecuzione e il programma verrà chiuso.


0

Usa " this.FinishAndRemoveTask();" - chiude correttamente l'applicazione

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.