Android 启用GPS定位后,AlertDialog未被禁用

Android 启用GPS定位后,AlertDialog未被禁用,android,location,android-alertdialog,Android,Location,Android Alertdialog,我有一个带有自定义布局的警报对话框,当gps或网络未启用时,它将弹出,以便用户能够启用它们 代码如下: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get Location Manager and check for GPS & Networ

我有一个带有自定义布局的警报对话框,当gps或网络未启用时,它将弹出,以便用户能够启用它们

代码如下:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    // Get Location Manager and check for GPS & Network location services
    final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) || !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View mView = getLayoutInflater().inflate(R.layout.activity_gps_alert_dialog, null);
        Button positiveBtn = (Button) mView.findViewById(R.id.positiveBtn);
        final Button negativeBtn = (Button) mView.findViewById(R.id.negativeBtn);
        builder.setView(mView);
        final AlertDialog dialog = builder.create();
        positiveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show location settings when the user acknowledges the alert dialog
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);

            }
        });

        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

问题是,即使GPS和网络已启用,此弹出对话框仍在屏幕上,即使用户通过它启用,alertdialog仍会保留在屏幕上。

用户按下肯定按钮后,必须使用
dialog.didmiss()关闭对话框。

    positiveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Show location settings when the user acknowledges the alert dialog
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
            dialog.didmiss()
        }
    });
对于另一部分,即使启用了gps和网络,也会弹出对话框,请参见以下文章:

好的,谢谢,当用户按下按钮时,它会关闭,但如果gps和网络已启用,当我使用应用程序时,它仍会弹出……有什么想法吗?我在任何地方都找不到我的答案:/谢谢你的时间,我的朋友!如果您阅读了我提到的链接,您应该意识到您使用的If语句虽然符合逻辑,但并不可靠。