Android 捕獲返回鍵徹底關閉應用程序 – Android移動開發技術文章_手機開發 Android移動開發教學課程

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


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


//捕獲按下鍵盤上返回按鈕
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            new AlertDialog.Builder(this)
                    // .setIcon(R.drawable.services)
                    .setTitle(R.string.prompt)
                    .setMessage(R.string.quit_msg)
                    .setNegativeButton(R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                }
                            })
                    .setPositiveButton(R.string.confirm,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    finish();
                                }
                            }).show();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    //徹底退出程序
    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
        // 或者下面這種方式
        // android.os.Process.killProcess(android.os.Process.myPid());
    }

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *