在运行时请求位置权限
我有一个查询,为Location
实现了RuntimePermission
.当我尝试requestLocationUpdates
时,我得到了LintError
提示我为该行添加PermissionCheck
.考虑到我实现了运行时权限.这就是它的样子,
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);
}
我的主类实现了onRequestPermissionsResult
回调.看起来像
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;
}
在授予权限后,我再次请求位置更新.但是它再次显示LintError
添加PermissionCheck
.请参考下图
After the permission is granted, I request location updates again. But it again shows LintError
to add the PermissionCheck
. Refer the below image
在onRequestPermissionsResult
中请求requestLocationUpdate
之前,尝试尝试checkSelfPermission
,错误消失了.像下面的代码.
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!
您确实需要检查checkSelfPermission,因为在最新的OS 6(棉花糖)中,您可以通过进入设置来撤消为应用程序授予的权限.
因此,即使用户在安装期间已授予应用程序权限,在运行时,您也需要仔细检查您的应用程序是否仍具有该权限或用户已撤消这些权限.
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.