Android回到键处理(事件)

Android返回键处理(事件)
方式一:按返回键显示退出提示框( 自定义提示框架可以参考[ Android使用自定义AlertDialog(退出提示框) ] )
方式二:按返回键不退出应用,返回主页面(即与按Home键操作一样)
方式一:
public class WelcomeActivity extends Activity {
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 如果是返回键,直接返回到桌面
if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){
                   showExitGameAlert();
}

return super.onKeyDown(keyCode, event);
}

private void showExitGameAlert() {
final AlertDialog dlg = new AlertDialog.Builder(this).create();
dlg.show();
Window window = dlg.getWindow();
window.setContentView(R.layout.shrew_exit_dialog);
ImageButton ok = (ImageButton) window.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
exitApp();
}
});

ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dlg.cancel();
}
});
}
}
方式2

public class SenseSoccerScoreActivity extends Activity {
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 如果是返回键,直接返回到桌面
                // 经过测试,如果是乐Phone返回桌面会报错
if(keyCode == KeyEvent.KEYCODE_BACK){
// 创建退出系统提示框
if(notSupportKeyCodeBack()){
                   new AlertDialog.Builder(this)
                    .setMessage(this.getText(R.string.sure_exit_app).toString())
                    .setPositiveButton(R.string.text_ok, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
            exitApp(); // 退出应用处理
               }
            })
            .setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
            }).create().show();
} else {
// 返回桌面,经测试,有一些手机不支持,查看 notSupportKeyCodeBack 方法
Intent i= new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
return false;
}
}
return super.onKeyDown(keyCode, event);
}
        // 经过测试,如果是乐Phone返回桌面会报错
private boolean notSupportKeyCodeBack(){
if("3GW100".equals(Build.MODEL) 
                         || "3GW101".equals(Build.MODEL)
                         || "3GC101".equals(Build.MODEL)) {
return true;
}
return false;
}
}