Android 安卓:如何让AlertDialog在点击ok按钮时消失?

Android 安卓:如何让AlertDialog在点击ok按钮时消失?,android,android-alertdialog,Android,Android Alertdialog,我问同样的问题,这是在下面的链接之前提出的,但这些链接中提出的解决方案不适合我,所以我再次张贴 基本上,我正在创建一个AlertDialog builder,通知用户请求启用使用数据访问设置,当按下OK按钮时,设置菜单打开。当我按“后退”按钮返回应用程序时,AlertDialog仍然可用,尽管我希望返回应用程序时会被取消 public void show_alert(){ AlertDialog.Builder builder = new AlertDialog.Buil

我问同样的问题,这是在下面的链接之前提出的,但这些链接中提出的解决方案不适合我,所以我再次张贴

基本上,我正在创建一个AlertDialog builder,通知用户请求启用使用数据访问设置,当按下OK按钮时,设置菜单打开。当我按“后退”按钮返回应用程序时,AlertDialog仍然可用,尽管我希望返回应用程序时会被取消

    public void show_alert(){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("This application requires access to the Usage Stats Service. Please " +
                        "ensure that this is enabled in settings, then press the back button to continue ");
    builder.setCancelable(true);

    builder.setPositiveButton(
            "OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                    startActivity(intent);
                    dialog.dismiss();
                }
            });

    builder.show();
    return;
}


有什么提示说明这里可能出了什么问题吗?

请在测试后编辑:

我在6.0.1上测试了OPs代码,它的行为符合预期——即,在单击“确定”后,对话框被取消。我将在下面留下我的初始答案,作为一个同样有效的选择。可以找到其他替代方案


您可以从
builder.show()
方法获取警报对话框的引用:

mMyDialog=builder.show()

onClick
方法中:

mMyDialog.disclose()

全样本:

AlertDialog mMyDialog; // declare AlertDialog
public void show_alert(){
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("This application requires access to the Usage Stats Service. Please " +
                    "ensure that this is enabled in settings, then press the back button to continue ");
  builder.setCancelable(true);

  builder.setPositiveButton(
        "OK",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {

                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                startActivity(intent);
                mMyDialog.dismiss(); // dismiss AlertDialog
            }
        });

  mMyDialog = builder.show(); // assign AlertDialog
  return;
}

你好谢谢你的输入,但是上面发布的代码对我不起作用。当我从“设置”页面按“后退”按钮时,该对话框仍然可用。我正在安卓7.0手机上运行此代码,我也尝试了您链接中的其他建议,但没有成功。@Pagar是对话框关闭后或您从设置返回时再次调用的
show\u alert
方法吗?很抱歉,混淆了,它现在起作用了,在调用序列中存在一些同步问题,我在仔细查看代码时发现了这些问题。谢谢你的帮助!