How to quit android application programmatically

前端 未结 30 1947
迷失自我
迷失自我 2020-11-22 03:06

I Found some codes for quit an Android application programatically. By calling any one of the following code in onDestroy() will it quit application entirely?

相关标签:
30条回答
  • 2020-11-22 03:09

    The correct and exact solution to quit the app on button click is using the below code:

    //On Button Back pressed event

    public void onBackPressed()
    { 
       moveTaskToBack(true);
       finish();
    }
    
    0 讨论(0)
  • 2020-11-22 03:09

    This will kill anything ;)

    int p = android.os.Process.myPid();
    android.os.Process.killProcess(p);
    
    0 讨论(0)
  • 2020-11-22 03:12

    I think that application should be kill in some case. For example, there is an app can be used only after login. The login activity has two buttons, 'login' and 'cancel'. When you click 'cancel' button, it definitely means 'Terminate the app'. Nobody wants the app alive in the background. So I agree that some cases need to shut down the app.

    0 讨论(0)
  • 2020-11-22 03:12

    It depends on how fast you want to close your app.

    A safe way to close your app is finishAffinity();

    It closes you app after all processes finished processing. This may need some time. If you close your app this way, and restart it after a short time, it is possible that your new application runs in the same process. With all the not finished processes and singleton objects of the old application.

    If you want to be sure, that your app is closed completly use System.exit(0);

    This will close your app immediatly. But it is possible, that you damage files that your app has open or an edit on shared preferences does not finish. So use this carefully.

    If you use watchdog in combination with a long running task, you can see the influences of the different methods.

    new ANRWatchDog(2000).setANRListener(new ANRWatchDog.ANRListener() {
        public void onAppNotResponding(ANRError error) {
            MainActivity.this.finishAffinity();
            System.exit(0);
        }
    }).start();
    for(int i = 0; i < 10; ++i){
        --i;
    }
    

    This kills your app after 2 seconds without displaying an ANR dialog or something like that. If you remove System.exit(0), run this code and restart the app after it is closed, you will experience some strange behaviour, because the endless loop is still running.

    0 讨论(0)
  • 2020-11-22 03:12
    public void quit() {
            int pid = android.os.Process.myPid();
            android.os.Process.killProcess(pid);
            System.exit(0);
        }
    
    0 讨论(0)
  • 2020-11-22 03:12

    Try this

    int pid = android.os.Process.myPid();
    android.os.Process.killProcess(pid);
    
    0 讨论(0)
提交回复
热议问题