Android -- 重写android返回键

在Activity里面加入下面代码:

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 
            showDialog(APP_EXIT); 
            return true; 
        } else 
            return super.onKeyDown(keyCode, event); 
    } 
    
    @Override 
    protected Dialog onCreateDialog(int id) { 
        if (id == APP_EXIT) { 
            return new AlertDialog.Builder(BaseActivity.this) 
                    .setMessage("是否退出程序?") 
                    .setTitle("用户退出") 
                    .setPositiveButton("确定", 
                            new DialogInterface.OnClickListener() { 
    
                                public void onClick(DialogInterface dialog, 
                                        int which) { 
                                    dialog.dismiss(); 
                                    android.os.Process 
                                            .killProcess(android.os.Process 
                                                    .myPid()); 
                                    finish(); 
    
                                } 
                            }) 
                    .setNegativeButton("取消", 
                            new DialogInterface.OnClickListener() { 
    
                                public void onClick(DialogInterface dialog, 
                                        int which) { 
                                    dialog.dismiss(); 
    
                                } 
                            }).create(); 
    
        } 
        return null; 
    
    } 

你可能感兴趣的:(重写android返回键)