package com.example.keyevent; import android.os.Bundle; import android.view.KeyEvent; import android.app.Activity; /** * Demo描述: * 处理Back键按下事件 * * 注意事项: * 以下两种方法勿一起使用 */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * 监听Back键按下事件,方法1: * super.onBackPressed()会自动调用finish()方法执行 onDestroy(),关闭 * 当前Activity. * 若要屏蔽Back键盘,注释该行代码即可 */ @Override public void onBackPressed() { super.onBackPressed(); System.out.println("按下了back键 onBackPressed()"); } /** * 监听Back键按下事件,方法2: * 在此处返回false,所以会继续传播该事件. 继续执行super.onKeyDown(keyCode, event); */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { System.out.println("按下了back键 onKeyDown()"); return false; }else { return super.onKeyDown(keyCode, event); } } @Override protected void onDestroy() { super.onDestroy(); System.out.println("执行 onDestroy()"); } }