Think: How to exit the program safely?
Finish is the Activity class. It only applies to the Activity. When finish () is called, the Activity is pushed to the background, and the memory is not released immediately. The Activity resources are not cleared; when System. when exit (0), the entire process is killed, and the resources occupied by the activity are also released.
When developing android applications, you often press the return key (that is, keyCode = KeyEvent. KEYCODE_BACK) to close the program. In most cases, the application is still running in the task. In fact, this is not the result we want.
We can do this. When a user clicks the custom exit button or return key (capture action is required), We forcibly exit the application in onDestroy () or directly kill the process, the specific operation code is as follows:
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
// Press the return button on the keyboard
If (keyCode = KeyEvent. KEYCODE_BACK ){
New AlertDialog. Builder (this)
. SetIcon (R. drawable. services)
. SetTitle (R. string. prompt)
. SetMessage (R. string. quit_desc)
. SetNegativeButton (R. string. cancel, new DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
}
})
. SetPositiveButton (R. string. confirm, new DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int whichButton ){
Finish ();
}
}). Show ();
Return true;
} Else {
Return super. onKeyDown (keyCode, event );
}
}
@ Override
Protected void onDestroy (){
Super. onDestroy ();
System. exit (0 );
// Or the following method
// Android. OS. Process. killProcess (android. OS. Process. myPid ());
}
From fulinwsuafcie's column