警报对话框多次调用

时间:2017-08-13 16:38:43

标签: android android-alertdialog android-lifecycle

每次用户输入应用程序时,onResume()都在调用。如果用户没有响应警报对话框,那么对话框就会累积。我想检查已经显示的对话框。

我在这里找到了很好的答案:Prevent dialog to be opened multiple times when resuming activityHow 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();
    }

2 个答案:

答案 0 :(得分:2)

你可以做的是将boolean isDialogBox显示在sharedPreferences中并使其成立。当用户单击dialogBox的正面或负面按钮时。并检查onResume

中isDialogBox是否为true

将此代码放入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();
}

答案 1 :(得分:1)

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

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

}