启用GPS定位后,不会禁用AlertDialog

时间:2018-07-27 06:24:42

标签: android location alertdialog

我有一个警报对话框,该对话框具有自定义布局,当未启用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和网络,并且即使用户启用了该对话框,警报对话框仍然会停留在屏幕上。

1 个答案:

答案 0 :(得分:0)

用户按下肯定按钮后,必须使用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和网络,该对话框也会弹出,请参阅以下文章: isProviderEnabled(LocationManager.NETWORK_PROVIDER) return false isProviderEnabled(LocationManager.GPS_PROVIDER) always returns false in android 2.3 GPS isProviderEnabled always return false LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is not reliable, why?