多次调用警报对话框

Alert dialog calling multiple times

每次用户进入应用程序时,都会调用 onResume()。如果用户没有对警告对话框做出响应,那么对话框就会不断累积。我想检查是否已显示对话框。

我在这里找到了很好的答案:Prevent dialog to be opened multiple times when resuming activity and here How do I show only one Dialog at a time? 但在我的代码中实现它时总是出现一些错误

警报对话框

private AlertDialog.Builder showGPSDialog(Context con) {

    AlertDialog.Builder builder = new AlertDialog.Builder(con);
    builder.setTitle("Enable GPS");
    builder.setMessage("Please enable GPS");

    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            startActivity(
                    new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    });
    builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    return builder;
}

onResume()

LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if(!isEnabled) {
        showGPSDialog(MapsActivity.this).show();
    }

只需关闭 onPause 方法上的对话框,您将只能显示一个对话框

@Override
protected void onPause(){
super.onPause();

}

您可以做的是将 boolean isDialogBox 显示在 sharedPreferences 中并使其为真。当用户单击对话框的肯定或否定按钮时。并在 onResume

中检查 isDialogBox 是否为真

把这段代码放在oncreate

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); 
private AlertDialog.Builder showGPSDialog(Context con) {

    AlertDialog.Builder builder = new AlertDialog.Builder(con);
    builder.setTitle("Enable GPS");
    builder.setMessage("Please enable GPS");

    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        prefs.edit().putBoolean("isShown", true).commit();
            startActivity(
                    new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    });
    builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
        prefs.edit().putBoolean("isShown", true).commit()
            dialog.dismiss();
        }
    });
    return builder;
}

这在 onResume 中

LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

if(!(prefs.getBoolean("isShown", false))) {
    showGPSDialog(MapsActivity.this).show();
}