MainActivity is as follows:
Copy codeThe Code is as follows: package cn. testnbackpressed;
Import android. OS. Bundle;
Import android. view. KeyEvent;
Import android. app. Activity;
/**
* Demo description:
* Process the Back key press event
*
* Note:
* Do not use the following two methods together
*/
Public class MainActivity extends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
}
/**
* Listen to the Back key press event, Method 1:
* Note:
* Super. onBackPressed () automatically calls the finish () method and closes
* Current Activity.
* To shield the Back keyboard, just comment out the line of code.
*/
@ Override
Public void onBackPressed (){
Super. onBackPressed ();
System. out. println ("the back key onBackPressed ()" is pressed ()");
}
/**
* Listen to the Back key press event, Method 2:
* Note:
* Indicates whether the event can be fully processed.
* False is returned here, so the event will continue to be propagated.
* In a specific project, the return value depends on the actual situation.
*/
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK )){
System. out. println ("the back key onKeyDown ()" is pressed ()");
Return false;
} Else {
Return super. onKeyDown (keyCode, event );
}
}
@ Override
Protected void onDestroy (){
Super. onDestroy ();
System. out. println ("execute onDestroy ()");
}
}
Main. xml is as follows: Copy codeThe Code is as follows: <RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
>
<TextView
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "two methods for processing the Back key"
Android: layout_centerInParent = "true"
Android: textSize = "20sp"
/>
</RelativeLayout>