Close application and launch home screen on Android

后端 未结 21 2036
我在风中等你
我在风中等你 2020-11-22 07:33

I have two different activities. The first launches the second one. In the second activity, I call System.exit(0) in order to force the application to close, bu

21条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 08:03

    Android has a mechanism in place to close an application safely per its documentation. In the last Activity that is exited (usually the main Activity that first came up when the application started) just place a couple of lines in the onDestroy() method. The call to System.runFinalizersOnExit(true) ensures that all objects will be finalized and garbage collected when the the application exits. For example:

    public void onDestroy() {
        super.onDestroy();
    
        /*
         * Notify the system to finalize and collect all objects of the
         * application on exit so that the process running the application can
         * be killed by the system without causing issues. NOTE: If this is set
         * to true then the process will not be killed until all of its threads
         * have closed.
         */
        System.runFinalizersOnExit(true);
    
        /*
         * Force the system to close the application down completely instead of
         * retaining it in the background. The process that runs the application
         * will be killed. The application will be completely created as a new
         * application in a new process if the user starts the application
         * again.
         */
        System.exit(0);
    }
    

    Finally Android will not notify an application of the HOME key event, so you cannot close the application when the HOME key is pressed. Android reserves the HOME key event to itself so that a developer cannot prevent users from leaving their application.

提交回复
热议问题