Android AlerDialog 已经显示了吗?

Android AlerDialog is showing already?

如果 AlertDialog 已经显示,我该如何阻止它显示?我到处搜索并使用不同的解决方案来为我的项目工作,但是我有一个每 5 秒运行一次的循环并调用 AlertDialog 方法(showSettingsAlert()),每次一个新的 AlertDialog 堆叠在前一个上。

我希望该方法在开始时检查它是否已经显示对话框。

这是我的代码:

public AlertDialog Dialog;
public void showSettingsAlert() {
  if (Dialog != null && Dialog.isShowing()) {
    return;
  } else {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("GPS Disabled");

    alertDialog.setMessage("Do you want to go to location settings menu?");

    alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
      }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });
    Dialog = alertDialog.create();
    Dialog.show();
  }
}

这样做,

//check dialog open method
public boolean checkDialogOpen()
    {
        if (Dialog!= null && Dialog.isShowing())
            return true;
        else
            return false;
    }

您的更新代码,

public AlertDialog Dialog;

public void showSettingsAlert() {

  if (checkDialogOpen()) 
    return;

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("GPS Disabled");

    alertDialog.setMessage("Do you want to go to location settings menu?");

    alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
      }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });
    Dialog = alertDialog.create();
    Dialog.show();
  }
}