Java代码中的Android位置权限检查

时间:2016-03-13 21:51:49

标签: android permissions gps location maps

我正在尝试在API 23上的Google MapsActivity上使用Android位置服务。我在清单文件中具有以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

当我尝试使用时:

mMap.setMyLocationEnabled(true);

它显示生成权限检查代码的错误(如下所示)。而且我不知道该怎么进去;似乎条件语句已经在进行必要的检查。

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

似乎我在此条件中输入的任何内容都会导致错误。

1 个答案:

答案 0 :(得分:2)

试试这个:

if (ContextCompat.checkSelfPermission(App.getContext(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

                    ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
                }

            } else { // no need to ask for permission

                // start to find location...
            }

并添加:

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // start to find location...

            } else { // if permission is not granted

                // decide what you want to do if you don't get permissions
            }
        }
    }

LOCATION_PERMISSION_REQUEST_CODE是您在班级中设置的final int(例如1252)。

另请阅读this,了解权限最佳做法。