Android 中 获取“back”键和“home”键,并为此附加功能

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME ) {
            showDialog(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        return new AlertDialog.Builder(this).setTitle(R.string.base_title)
                .setPositiveButton(R.string.base_pos,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                BaseApplication appState = (BaseApplication)BaseActivity.this.getApplication();
                                appState.stopService();
                                int pid = android.os.Process.myPid();
                                android.os.Process.killProcess(pid);
                            }
                        }).setNegativeButton(R.string.base_neg,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                            }
                        }).create();

    }



 而对于Android 2.0开始又多出了一种新的方法,对于Activity 可以单独获取Back键的按下事件,直接重写onBackPressed方法即可,代码如下

@Override
public void onBackPressed() {
// 这里处理逻辑代码,大家注意:该方法仅适用于2.0或更新版的sdk
return;
}

你可能感兴趣的:(android,dialog)