Android运行时位置服务权限

时间:2016-08-29 21:31:15

标签: android google-maps permissions

我有一个应用程序,我希望通过在打开活动时删除别针来向用户显示位置" Map"。我还想显示用户的位置,如果标记出现问题,那么地图就会以用户所在位置为中心。

与其他许多人一样,我有一天注意到我的应用没有显示用户在Android 6.0上方的位置。所以我开始搜索SO和Google并找到一些线程和教程。事实证明,我必须检查权限是否已经可用,或者是否需要通过调用 checkSelfPermissions 方法来授予它们,如果它们尚未被授予,我必须通过调用< EM> requestPermissions 。当他们被请求时,我想设置标记并显示用户位置(或者如果某些内容与附加内容中的标记信息搞混,则将地图置于中心位置)。我想用我的方法setUpMarker做这个。下面是我的 onMapReady (在地图准备就绪时调用)和 onRequestPermissionsResult (当有来自权限请求的用户响应时调用)方法:

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission is not yet available and needs to be asked for
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // We provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example if the user has previously denied the permission.
            new AlertDialog.Builder(Map.this)
                    .setMessage("To show the location the permission is needed")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(Map.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION_REQUEST_ID);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            // Permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION_REQUEST_ID);
        }

    } else {
        // Permission is already available
        setUpMarker();
    }

}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case LOCATION_PERMISSION_REQUEST_ID: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // The permission request was granted, we set up the marker
                setUpMarker();
            } else {
                // The permission request was denied, we make the user aware of why the location is not shown
                Toast.makeText(this,"Since the permission wasn't granted we can't show the location",Toast.LENGTH_LONG).show();
            }
            return;
        }

    }
}

现在,当我想启用用户位置以及何时想要将地图置于用户位置中心时,我的setUpMarker方法仍然出现错误。我得到的错误是:

Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with 'checkPermission') or explicitly handle a potential 'SecurityException'.

但我已经检查了权限!这是我的setUpMarker:

private void setUpMarker() {
    //HERE I GET THE ERROR
    mMap.setMyLocationEnabled(true); 

    if(!getIntent().getExtras().isEmpty()) {
        // Latitude and longitude was retrieved successfully, set up marker

         ...

    } else {
        // Latitude and longitude was not retrieved, zoom to current location

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        // AND HERE I GET THE ERROR TOO
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); 
        if (location != null) {
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(), location.getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude()))
                    .zoom(17)
                    .bearing(90)
                    .tilt(40)
                    .build();
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        }

    }
}

如何让应用程序记住权限,或以其他方式解决此问题?我已经检查过类似的线程,但似乎都没有这种问题。

1 个答案:

答案 0 :(得分:1)

这是Lint错误 - 您可以向该方法添加相同的ContextCompat.checkSelfPermission调用(即使您知道它将始终返回已授予),以取悦Lint或抑制Lint错误。< / p>