Android 程序退出确认功能开发 .

来源:互联网 发布:淘宝怎么添加公益宝贝 编辑:程序博客网 时间:2024/05/16 01:24
   程序都需要退出确认功能,方式有很多种。不多说。

方法一:

[java] view plaincopyprint?
  1. @Override  
  2.     public boolean dispatchKeyEvent(KeyEvent event) {  
  3.         if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {  
  4.             if (event.getAction() == KeyEvent.ACTION_DOWN  
  5.                     && event.getRepeatCount() == 0) {  
  6.                 this.confirmExit();// 这是自定义的代码  
  7.             }  
  8.             return true;  
  9.         }  
  10.   
  11.         return super.dispatchKeyEvent(event);  
  12.     }  
  13.   
  14.     private void confirmExit() {  
  15.         // 退出确认   
  16.         AlertDialog.Builder ad = new AlertDialog.Builder(PGisMainActivity.this);  
  17.         ad.setTitle("退出");  
  18.         ad.setIcon(R.drawable.ic_launcher);  
  19.         ad.setMessage("是否退出系统?");  
  20.         ad.setPositiveButton("是"new DialogInterface.OnClickListener() {  
  21.             // 退出按钮   
  22.             @Override  
  23.             public void onClick(DialogInterface dialog, int i) {  
  24.                 isRunning = false;  
  25.                   
  26.             }  
  27.         });  
  28.         ad.setNegativeButton("否"new DialogInterface.OnClickListener() {  
  29.             @Override  
  30.             public void onClick(DialogInterface dialog, int i) {  
  31.                 // 不退出不用执行任何操作  
  32.             }  
  33.         });  
  34.         ad.show();// 显示对话框   
  35.     }  


方法二:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. @Override  
  2.     public boolean onKeyDown(int keyCode, KeyEvent event) {  
  3.         if (keyCode == KeyEvent.KEYCODE_BACK) {  
  4.             exitApplication();  
  5.         }  
  6.         return true;  
  7.     }  
  8. private void exitApplication() {  
  9.         Builder builder = new Builder(this);  
  10.         builder.setIcon(R.drawable.ic_launcher);  
  11.         builder.setTitle("退出");  
  12.         builder.setMessage("确定退出吗?");  
  13.         builder.setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  14.   
  15.             public void onClick(DialogInterface dialog, int which) {  
  16.                 System.exit(0);  
  17.   
  18.             }  
  19.         });  
  20.         builder.setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  21.   
  22.             public void onClick(DialogInterface arg0, int arg1) {  
  23.   
  24.             }  
  25.         });  
  26.         builder.show();  
  27.     }  


0 0