如何显示对话框以确认用户希望退出 activity?

How to show a dialog to confirm that the user wishes to exit an activity?

我正在使用下面的 onBackpress 方法,但这不起作用,我仍然悔改地点击后退按钮来了同样的 activity 没有退出当前 activity 请解决我的问题。

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        // Your Dialog Code is here.

        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        ProfileActivity.super.onBackPressed();
                        finish();
                    }
                }).create().show();
    }

删除 ProfileActivity.super.onBackPressed(); 它会起作用。

.setCancelable(false)AlertDialog

结合使用
@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    // Your Dialog Code is here.

    new AlertDialog.Builder(this)
            .setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface arg0, int arg1) {
                    ProfileActivity.super.onBackPressed();
                    finish();
                }
            }).create().show();
}

删除此 ProfileActivity.super.onBackPressed();

添加

.setCancelable(false)