android 按返回退出应用

来源:互联网 发布:java 泛型 getclass 编辑:程序博客网 时间:2024/05/29 11:04
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;

}


finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,杀死了整个进程,

这时候活动所占的资源也会被释放。

在开发android应用时,常常通过按返回键(即keyCode == KeyEvent.KEYCODE_BACK)就能关闭程序,其实大多情况下该应用还在任务里运行着,其实这不是我们想要的结果。

我们可以这样做,当用户点击自定义的退出按钮或返回键时(需要捕获动作),我们在onDestroy()里强制退出应用,或直接杀死进程。

 

[java] view plaincopy
  1. @Override  
  2.   
  3. public boolean onKeyDown(int keyCode, KeyEvent event) {  
  4.   
  5. //按下键盘上返回按钮  
  6.   
  7. if(keyCode == KeyEvent.KEYCODE_BACK){  
  8.   
  9.    
  10.   
  11. new AlertDialog.Builder(this)  
  12.   
  13. .setIcon(R.drawable.services)  
  14.   
  15. .setTitle(R.string.prompt)  
  16.   
  17. .setMessage(R.string.quit_desc)  
  18.   
  19. .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {  
  20.   
  21. @Override  
  22.   
  23. public void onClick(DialogInterface dialog, int which) {  
  24.   
  25. }  
  26.   
  27. })  
  28.   
  29. .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {  
  30.   
  31. public void onClick(DialogInterface dialog, int whichButton) {  
  32.   
  33. finish();  
  34.   
  35. }  
  36.   
  37. }).show();  
  38.   
  39. return true;  
  40.   
  41. }else{  
  42.   
  43. return super.onKeyDown(keyCode, event);  
  44.   
  45. }  
  46.   
  47. }  
  48.   
  49.    
  50.   
  51.    
  52.   
  53. @Override  
  54.   
  55. protected void onDestroy() {  
  56.   
  57. super.onDestroy();  
  58.   
  59. System.exit(0);  
  60.   
  61. //或者下面这种方式  
  62.   
  63. //android.os.Process.killProcess(android.os.Process.myPid());   
  64.   
  65. }  

原创粉丝点击