Androidz之返回键退出程序

fmms 13年前

Android按返回键退出程序,没什么好说的,直接贴代码:

public boolean onKeyDown(int keyCode, KeyEvent event) {     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {      // 确认对话框      final AlertDialog isExit = new AlertDialog.Builder(this).create();      // 对话框标题      isExit.setTitle("系统提示");      // 对话框消息      isExit.setMessage("确定要退出吗?");      // 实例化对话框上的按钮点击事件监听      DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {       public void onClick(DialogInterface dialog, int which) {        switch (which) {        case AlertDialog.BUTTON1:// "确认"按钮退出程序                   NotificationManager notificationManager = (NotificationManager) MainActivity.this                          .getSystemService(NOTIFICATION_SERVICE);            notificationManager.cancel(0);            String packagename = getPackageName();          ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);           finish();          if(getSystemVersion()<8){                        manager.restartPackage(getPackageName());           }else{                      manager.killBackgroundProcesses(packagename);           }           break;        case AlertDialog.BUTTON2:// "取消"第二个按钮取消对话框         isExit.cancel();         break;        default:         break;        }       }      };      // 注册监听      isExit.setButton("确定", listener);      isExit.setButton2("取消", listener);      // 显示对话框      isExit.show();      return false;     }     return false;    }