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;

}


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. }  

發佈了19 篇原創文章 · 獲贊 9 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章