Requesting Location Permission at Runtime

巧了我就是萌 提交于 2019-12-11 10:05:57

问题


I have a query implementing RuntimePermission for Location. When I tried to requestLocationUpdates, I got LintError suggesting me to add PermissionCheck for that line. Considering that I implemented run-time permissions. So this is how it looks,

if (isNetworkEnabled() && networkListener != null) {
        if (ActivityCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(context,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(activity, new String[]
                    {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        } else
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkListener);
}

And my main class implements onRequestPermissionsResult callback. This looks like,

switch (requestCode) {
        case REQUEST_LOCATION:
                if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkListener);
                } else
                    Message.displayToast(context, "Without enabling permission, you can't access this feature");
            break;
    }

After the permission is granted, I request location updates again. But it again shows LintError to add the PermissionCheck. Refer the below image

Just for try I checkSelfPermission before requesting for requestLocationUpdate inside onRequestPermissionsResult and the error is gone. Like below code.

if (ActivityCompat.checkSelfPermission(context, permissions[0]) == PackageManager.PERMISSION_GRANTED &&
                            ActivityCompat.checkSelfPermission(context, permissions[1]) == PackageManager.PERMISSION_GRANTED)

So, my question is do I need to check the permission once again if the user granted the permission? Correct me if I'm wrong!


回答1:


You do need to check for checkSelfPermission because with latest OS 6 (Marshmallow) you can revoke the permissions granted for an app by going into settings.
So even if user has granted the permissions to app during installation time, at runtime you need to doublecheck whether your app still has the permissions or user has revoked those permissions.



来源:https://stackoverflow.com/questions/35311514/requesting-location-permission-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!