Android手机定位未开启,跳转到GPS开启页面

在Android进行手机设置时,会出现GPS关闭的情况,这时应该弹出一个窗口提示用户开启GPS,然后开启后重启定位监听。

提示窗口:

 private void openGPS() {
        new AlertDialog.Builder(MapActivity.this)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle(R.string.information)
                .setMessage("没有开启定位")
                .setNegativeButton(R.string.cancel,null)
                .setPositiveButton(R.string.open, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent,887);
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

开启监听:

private void startLocation() {
        Log.e(Tag, "开始定位");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        //ACCURACY_HIGH/ACCURACY_LOW精度选择
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //高度
        criteria.setAltitudeRequired(true);
        //方位信息
        criteria.setBearingRequired(true);
        //是否允许付费
        criteria.setCostAllowed(true);
        //对电量的要求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        //速度
        criteria.setSpeedRequired(true);
        String locationProvider = locationManager.getBestProvider(criteria, true);
        Log.e(Tag, locationProvider);
        if (ActivityCompat.checkSelfPermission(MapActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MapActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
        } else {
            locationListener = new locateListener();
            locationManager.requestLocationUpdates(locationProvider, 1000, 1, locationListener);
            Log.e(Tag, "开始监听");
        }

    }


结果返回:

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case 887:
                //开启GPS,重新添加地理监听
                startLocation();
                break;
            default:break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }




你可能感兴趣的:(Android)