onResume() 后无法关闭 AlertDialog

Unable to close AlertDialog after onResume()

我检查 activity 启动时定位服务是否打开,如果没有打开,我将打开一个对话框来启动 "Enable Location Activity" 意图。从那里返回后,我会检查该位置是否真的已启用,如果是,我将关闭警报对话框。

理论上这应该可行,但是当我的 activity 恢复并调用 dialog.dismiss() 时绝对没有任何反应。

我的代码如下-:

public class LocationUtils {

private static AlertDialog dialog_ = null;

public static void checkAndEnableLocationServices(final Activity context) {
    LocationManager lm = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    System.out.println("gps_enabled = " + gps_enabled);
    System.out.println("network_enabled = " + network_enabled);

    if (!gps_enabled && !network_enabled) {
        // notify user
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setMessage("Location services are disabled");
        builder.setPositiveButton("Enable Location Services", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                // TODO Auto-generated method stub

                Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(myIntent);
                //get gps
            }
        });
        builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                context.finish();
            }
        });
        //For future reference.
        AlertDialog dialog = builder.create();

        dialog_ = dialog;

        dialog.show();
    } else {
        if(dialog_!=null) {
            dialog_.dismiss();
        }
    }
}

}

在我的主 activity 中,我有一个执行以下操作的 onResume 回调:

@Override
protected void onResume() {
    super.onResume();
    System.out.println("Activity resume()");
    LocationUtils.checkAndEnableLocationServices(this);
}

我错过了什么?为什么这是对话框没有关闭?代码没有抛出任何错误。这对我来说是一个糟糕的时刻。

如果未启用位置服务,您可以在单击肯定按钮时关闭对话框并在 OnResume 中显示它

您正在为本地警报对话框调用 alertDialog.show 方法。 替换代码,

   AlertDialog dialog = builder.create();
    dialog_ = dialog;

 dialog_ =  builder.create();
 dialog_.show

和 onResume()

    if(dialog_!=null) {
        dialog_.dismiss();
    }