Mainactivity as follows:
Packagecom.testnbackpressed;ImportAndroid.os.Bundle;Importandroid.view.KeyEvent;Importandroid.app.Activity;/*** Demo Description: * Handling back Key Press event * * NOTE: * The following two ways not to use together*/ Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); } /*** Listen to the back key press event, Method 1: * Note: * super.onbackpressed () will automatically call the finish () method to close * Current activity. * To block the back keyboard, comment the line code to*/@Override Public voidonbackpressed () {Super. onbackpressed (); System.out.println ("Press back Key onbackpressed ()"); } /*** Listen to the back key press event, Method 2: * Note: * The return value indicates whether the event can be fully processed * returns false here, so the event will continue to propagate. * The return value here is subject to availability in the specific project. */@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) { if(KeyCode = =keyevent.keycode_back)) {System.out.println ("Press back Key OnKeyDown ()"); return false; }Else { return Super. OnKeyDown (KeyCode, event); }} @Overrideprotected voidOnDestroy () {Super. OnDestroy (); System.out.println ("Execute OnDestroy ()"); } }
Main.xml 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 ways to handle the back key " android:layout_centerinparent= "true" android:textsize= "20sp" /> </ Relativelayout>
Monitoring and processing of return keys in Android apps