Como fechar o aplicativo Android?


157

Quero fechar meu aplicativo, para que ele não seja mais executado em segundo plano.

Como fazer isso? Esta é uma boa prática na plataforma Android?

Se eu confiar no botão "voltar", ele fechará o aplicativo, mas permanecerá em segundo plano. Existe até um aplicativo chamado "TaskKiller" apenas para matar esses aplicativos em segundo plano.



querendo saber por que alguém não gostaria que seu aplicativo fosse executado mesmo em segundo plano?
Darpan

Respostas:


139

O Android possui um mecanismo para fechar um aplicativo com segurança de acordo com sua documentação. Na última atividade encerrada (geralmente a principal atividade que surgiu quando o aplicativo foi iniciado), basta colocar algumas linhas no método onDestroy (). A chamada para System.runFinalizersOnExit (true) garante que todos os objetos sejam finalizados e o lixo coletado quando o aplicativo sair. Você também pode matar um aplicativo rapidamente via android.os.Process.killProcess (android.os.Process.myPid ()), se preferir. A melhor maneira de fazer isso é colocar um método como o seguinte em uma classe auxiliar e chamá-lo sempre que o aplicativo precisar ser morto. Por exemplo, no método de destruição da atividade raiz (assumindo que o aplicativo nunca elimine essa atividade):

Além disso, o Android não notificará um aplicativo sobre o evento da tecla HOME , portanto você não poderá fechar o aplicativo quando a tecla HOME for pressionada. O Android reserva o evento de chave HOME para si mesmo, para que um desenvolvedor não possa impedir que os usuários deixem seu aplicativo. No entanto, você pode determinar com a tecla HOME pressionada definindo um sinalizador para true em uma classe auxiliar que pressupõe que a tecla HOME foi pressionada e alterando o sinalizador para false quando ocorrer um evento que mostre que a tecla HOME não foi pressionada e, em seguida, verificando a tecla HOME pressionada no método onStop () da atividade.

Não se esqueça de manipular a tecla HOME em qualquer menu e nas atividades iniciadas pelos menus. O mesmo vale para a chave SEARCH . Abaixo estão alguns exemplos de classes para ilustrar:

Aqui está um exemplo de atividade raiz que mata o aplicativo quando ele é destruído:

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);
    }

}

Aqui está uma atividade abstrata que pode ser estendida para manipular a tecla HOME de todas as atividades que a estendem:

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;
    }
}

Aqui está um exemplo de uma tela de menu que lida com a tecla 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;
    }

}

Aqui está um exemplo de uma classe auxiliar que lida com a tecla HOME no aplicativo:

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
Isso deve matar o aplicativo inteiro chamado System.exit (0), incluindo todas as atividades em execução como parte do aplicativo. Todos os outros aplicativos continuarão em execução. Se você deseja matar apenas uma atividade no aplicativo, mas não todas as atividades no aplicativo, é necessário chamar o método finish () da atividade que deseja matar.
Danny Remington - OMS

2
Muito obrigado por este nfo. Estou fazendo um jogo com o AndEngine e quando eu terminava, mesmo em todas as atividades, o android ainda não estava totalmente limpo e, quando o jogo era relançado, ficava completamente danificado minhas texturas GL estavam com problemas etc. Então, depois de investigar, pensando que era o AndEngine, eu percebi que tinha que haver algo errado, porque o Android estava tentando preservar o processo quando eu queria sair dele. Todos os comentários "ah, você não deve chamar de saída, isso estraga a experiência do usuário" é um absurdo. O tempo em que um aplicativo deve permanecer aberto .......

17
Nenhum aplicativo de produção deve estar usando esse código. Nenhum aplicativo de produção deve chamar o código mostrado killApp(), pois o Google indicou que isso levará a um comportamento imprevisível.
CommonsWare

1
System.runFinalizersOnExit (true); O método foi preterido. Qual é a outra maneira de fechar um aplicativo com segurança (coleta de lixo) ?.
ajeesh

1
Não foi preterido no momento em que foi publicado originalmente. Como o AP atual era 7 e a API atual agora é 19, provavelmente existe outra maneira de fazer isso agora.
Danny Remington - OMS

68

SIM! Você certamente pode fechar seu aplicativo para que ele não esteja mais sendo executado em segundo plano. Como outros usuários comentaram, finish()é a maneira recomendada pelo Google que realmente não significa que seu programa esteja fechado.

System.exit(0);

Isso aí vai fechar o aplicativo, deixando nada em execução no background.However, utilizam esta com sabedoria e não deixar arquivos abertos, alças banco de dados aberto, as coisas etc.Estes normalmente ser limpo através do finish()comando.

Eu pessoalmente odeio quando escolho Sair em um aplicativo e ele realmente não sai.


44
O uso de System.exit () não é absolutamente recomendado.
CommonsWare

14
Não vou argumentar que não é o caminho recomendado, mas você pode fornecer uma solução que garanta que o aplicativo seja encerrado imediatamente em segundo plano? Caso contrário, o System.exit é o caminho a seguir até que o Google forneça um método melhor.
Cameron McBride

74
Quem decide que você não deveria, as mesmas pessoas que criaram um método que na verdade não sai? Se os usuários não quisessem que seus aplicativos fossem fechados, o quinto aplicativo pago mais popular não seria um matador de tarefas. As pessoas precisam de memória liberada e o sistema operacional principal não faz o trabalho.
Cameron McBride

19
Concordou que é desaconselhável, mas recebeu um voto positivo por fornecer uma resposta real à pergunta feita. Estou ficando muito cansado de ouvir "você realmente não quer fazer isso", sem nenhuma explicação de acompanhamento. O Android é um pesadelo absoluto em relação à documentação para esses tipos de coisas em comparação com o iPhone.
DougW

11
Não há benefício de memória no uso de assassinos de tarefas com o Android. O Android destruirá e limpará todos os aplicativos que não estiverem em primeiro plano, se o aplicativo precisar de mais memória. Em alguns casos, o Android reabre um aplicativo que foi fechado com o assassino de tarefas. O Android preencherá toda a memória não necessária com os aplicativos usados ​​recentes para diminuir o tempo de troca de aplicativos. NÃO CONSTRUA APLICATIVOS COM UM BOTÃO DE SAÍDA. NÃO USE UM GERENTE DE TAREFAS NO ANDROID. geekfor.me/faq/you-shouldnt-be-using-a-task-killer-with-android android-developers.blogspot.com/2010/04/...
Janusz

23

Foi assim que eu fiz:

Eu apenas coloquei

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

dentro do método que abre uma atividade e, em seguida, dentro do método de SOMECLASSNAME projetado para fechar o aplicativo que eu coloquei:

setResult(0);
finish();

E eu coloquei o seguinte na minha classe principal:

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

18

Apenas para responder minha própria pergunta agora, depois de tanto tempo (desde que o CommonsWare comentou a resposta mais popular dizendo que NÃO devemos fazer isso):

Quando eu quero sair do aplicativo:

  1. Inicio minha primeira atividade (tela inicial ou qualquer atividade que esteja atualmente na parte inferior da pilha de atividades) com FLAG_ACTIVITY_CLEAR_TOP(que encerrará todas as outras atividades iniciadas após ela, o que significa - todas elas). Apenas faça para ter essa atividade na pilha de atividades (não termine por algum motivo com antecedência).
  2. Eu chamo finish()essa atividade

É isso, funciona muito bem para mim.


3
Na verdade, isso não mata seu aplicativo. Ele ainda aparecerá na lista de aplicativos. Eu apenas mato todas as suas atividades.
Joris Weimar

1
FLAG_ACTIVITY_CLEAN_TOP não funciona para smartphones Sony. Você pode contornar isso adicionando android: clearTaskOnLaunch = "true" atributo à atividade no AndroidManifest.xml
Rusfearuth

10

Basta escrever este código no botão EXIT clique.

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

E no método onCreate () da sua MainActivity.class, escreva o código abaixo como primeira linha,

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

9

Não é possível usar as APIs da estrutura. É a critério do sistema operacional (Android) decidir quando um processo deve ser removido ou permanecer na memória. Isso ocorre por razões de eficiência: se o usuário decidir reiniciar o aplicativo, ele já estará lá sem que seja necessário carregar na memória.

Então não, não é desencorajado , é impossível fazê-lo.


4
Você sempre pode fazer algo como Inteiro z = null; z.intValue (); // pior resposta
Joe Plante

6
Verdade isso. Você também pode esmagar seu telefone contra a parede, que encerrará todos os aplicativos abertos se for aplicada pressão suficiente. Eu ainda não recomendaria. Atualizei minha postagem de acordo.
Matthias

@JoePlante que também deixa o aplicativo em segundo plano quando você abre o menu de aplicativos. Parece que é impossível.
usar o seguinte comando

8

Para sair de maneiras de aplicativos:

Caminho 1:

ligar finish();e substituir onDestroy();. Coloque o seguinte código em onDestroy():

System.runFinalizersOnExit(true)

ou

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

Caminho 2:

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

Caminho 3:

Quit();

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

Caminho 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();
}

Caminho 5:

Às vezes, a chamada finish()sai da atividade atual, não de todo o aplicativo. No entanto, há uma solução alternativa para isso. Toda vez que você iniciar um activity, inicie-o usando startActivityForResult(). Quando você deseja fechar o aplicativo inteiro, pode fazer algo como o seguinte:

setResult(RESULT_CLOSE_ALL);
finish();

Em seguida, defina o onActivityResult(...)retorno de chamada de cada atividade para que, quando activityretornar com o RESULT_CLOSE_ALLvalor, também chame 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);
}

Intenção intenção = nova Intenção (getApplicationContext (), LoginActivity.class); intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra ("EXIT", verdadeiro); startActivity (intenção); está funcionando super bem.
precisa saber é o seguinte

Comecei a Atividade A-> B-> C-> D. Quando o botão Voltar é pressionado na Atividade DI, quero ir para a Atividade A. Como A é o meu ponto de partida e, portanto, já na pilha, todas as atividades na parte superior de A são limpas e você não pode voltar para nenhuma outra Atividade de A @Override public boolean onKeyDown (int keyCode, evento KeyEvent) {if (keyCode == KeyEvent.KEYCODE_BACK) {Intenção a = nova Intenção (esta, classe A.); a.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity (a); return true; } retornar super.onKeyDown (keyCode, event); }
hitesh141 15/04

5

Foi assim que o Windows Mobile funcionou ... bem ... sempre! Aqui está o que a Microsoft tem a dizer sobre o assunto:

http://blogs.msdn.com/windowsmobile/archive/2006/10/05/The-Emperor-Has-No-Close.aspx (é triste que eu tenha lembrado o título da postagem do blog desde 2006? Encontrei o artigo no Google pesquisando "o imperador não tem fim" lol)

Em resumo:

Se o sistema precisar de mais memória enquanto o aplicativo estiver em segundo plano, ele será fechado. Mas, se o sistema não precisar de mais memória, o aplicativo permanecerá na RAM e estará pronto para voltar rapidamente na próxima vez que o usuário precisar.

Muitos comentários nesta pergunta em O'Reilly sugerem que o Android se comporta da mesma maneira, fechando aplicativos que não são usados ​​há um tempo apenas quando o Android precisa da memória que está usando.

Como esse é um recurso padrão, a alteração do comportamento para fechamento forçado alteraria a experiência do usuário. Muitos usuários estariam acostumados com a demissão gentil de seus aplicativos Android; portanto, quando eles descartam um com a intenção de retornar a ele depois de executar outras tarefas, eles podem ficar um pouco frustrados porque o estado do aplicativo é redefinido ou leva mais tempo abrir. Eu ficaria com o comportamento padrão, porque é o que é esperado.


5

A chamada do finish()método em uma Atividade tem o efeito desejado nessa atividade atual.


14
Não, não faz. Finaliza a Atividade atual, não o aplicativo. Se você terminar () a Atividade mais baixa da pilha de tarefas, seu aplicativo parecerá sair, mas o Android poderá decidir mantê-lo por tanto tempo quanto achar conveniente.
Matthias

De fato, no entanto, se você precisar sair totalmente do seu aplicativo, precisará chamar o método de conclusão para cada atividade e também pensar em quaisquer serviços que possa ter iniciado. Também editei a resposta inicial - desculpe pela omissão.
r1k0

3

nenhuma das respostas acima funciona bem no meu aplicativo

aqui está o meu código de trabalho

no seu botão de saída:

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();

esse código é para fechar qualquer outra atividade e colocar MainActivity no topo agora em seu MainActivity:

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

2

Coloque uma finish();declaração como abaixo:

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

finish();

LoginActivity.this.startActivity(myIntent);

Em toda atividade.


2
@Override
    protected void onPause() {

        super.onPause();

        System.exit(0);

    }

2

Copie o código abaixo e cole o arquivo AndroidManifest.xml em Primeira tag de atividade.

<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>     

Adicione também este código abaixo em todas as tags de atividade no arquivo AndroidManifest.xml

 android:finishOnTaskLaunch="true"

1

Não é possível com 2.3. Eu pesquisei muito e tentei muitos aplicativos. A melhor solução é instalar ambos (vá gerenciador de tarefas) e (reinicialização rápida). Quando usá-los juntos, ele funcionará e liberará a memória. Outra opção é atualizar para o Android Ice Cream Sandwich 4.0.4, que permite o controle (fechamento) de aplicativos.



1

O uso de finishAffinity()pode ser uma boa opção se você deseja fechar todas as atividades do aplicativo. De acordo com o Android Docs-

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 em manifesto:

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

Então você pode ligar CloseAppActivity.closeApp(fromActivity)e o aplicativo será fechado.


1

Basta escrever o seguinte código no 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

chamando finish (); no botão OnClick ou no menu

case R.id.menu_settings:

      finish();
     return true;

Como afirmado nos comentários de outras respostas, finish()não mata o aplicativo. Pode voltar para a intenção anterior ou aplicar um plano de fundo ao aplicativo.
Raptor

0

Acho que fechará sua atividade e todas as atividades secundárias relacionadas a ela.

public boolean onOptionsItemSelected(MenuItem item) {

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

        return super.onOptionsItemSelected(item);
    }

0

A melhor e mais curta maneira de usar a tabela System.exit.

System.exit(0);

A VM interrompe a execução e o programa será encerrado.


Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.