歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 徹底關閉應用程序 返回鍵的捕獲

Android 徹底關閉應用程序 返回鍵的捕獲

日期:2017/3/1 10:46:01   编辑:Linux編程

在開發Android應用時,常常通過按返回鍵(即keyCode == KeyEvent.KEYCODE_BACK)就能關閉程序,其實大多情況下該應用還在任務裡運行著,其實這不是我們想要的結果。

我們可以這樣做,當用戶點擊自定義的退出按鈕或返回鍵時(需要捕獲動作),我們在onDestroy()裡強制退出應用,或直接殺死進程,具體操作代碼如下:

  1. @Override
  2. public boolean onKeyDown(int keyCode, KeyEvent event) {
  3. //按下鍵盤上返回按鈕
  4. if(keyCode == KeyEvent.KEYCODE_BACK){
  5. new AlertDialog.Builder(this)
  6. .setIcon(R.drawable.services)
  7. .setTitle(R.string.prompt)
  8. .setMessage(R.string.quit_desc)
  9. .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
  10. @Override
  11. public void onClick(DialogInterface dialog, int which) {
  12. }
  13. })
  14. .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
  15. public void onClick(DialogInterface dialog, int whichButton) {
  16. finish();
  17. }
  18. }).show();
  19. return true;
  20. }else{
  21. return super.onKeyDown(keyCode, event);
  22. }
  23. }
  24. @Override
  25. protected void onDestroy() {
  26. super.onDestroy();
  27. System.exit(0);
  28. //或者下面這種方式
  29. //android.os.Process.killProcess(android.os.Process.myPid());
  30. }
Copyright © Linux教程網 All Rights Reserved