如何在用户通过按Android中的backKey关闭警报对话框时捕获事件

Cod*_*LaY 10 android

当用户按下后退键并尝试关闭对话框时我需要捕获一个事件我有这样的代码

AlertDialog alertDialog = new AlertDialog.Builder(AppNotification.this).create();
    alertDialog.setTitle("Caution");
    alertDialog.setMessage("Alert");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        finish();
    } });
    alertDialog.show();
}
Run Code Online (Sandbox Code Playgroud)

现在我已经给了用户一个选项,但是假设他按下后退键然后我需要执行一些其他操作.如何做到这一点?

Sni*_*per 26

这会对你有所帮助

alertDialog.setOnCancelListener(new OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        // Your code ...                
    }
});
Run Code Online (Sandbox Code Playgroud)