Listening and processing instances of the Back key in Android applications

  • 2020-05-17 06:23:17
  • OfStack

MainActivity is as follows:
 
package cn.testnbackpressed; 
import android.os.Bundle; 
import android.view.KeyEvent; 
import android.app.Activity; 
/** 
* Demo describe : 
*  To deal with Back Press the event  
* 
*  Matters needing attention : 
*  There are two ways 1 The use  
*/ 
public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
} 
/** 
*  Listening to the Back Press the event , methods 1: 
*  Pay attention to : 
* super.onBackPressed() Will automatically call finish() methods , Shut down  
*  The current Activity. 
*  If you want to block Back The keyboard , Just comment the line of code  
*/ 
@Override 
public void onBackPressed() { 
super.onBackPressed(); 
System.out.println(" Press the back key  onBackPressed()"); 
} 
/** 
*  Listening to the Back Press the event , methods 2: 
*  Pay attention to : 
*  Return value representation : Whether the event can be fully handled  
*  Return here false, So it will continue to spread the story . 
*  The return value here is project-specific . 
*/ 
@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
if ((keyCode == KeyEvent.KEYCODE_BACK)) { 
System.out.println(" Press the back key  onKeyDown()"); 
return false; 
}else { 
return super.onKeyDown(keyCode, event); 
} 

} 

@Override 
protected void onDestroy() { 
super.onDestroy(); 
System.out.println(" perform  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=" for Back Two ways of dealing with keys " 
android:layout_centerInParent="true" 
android:textSize="20sp" 
/> 
</RelativeLayout> 

Related articles: