这是我的代码,它工作得非常好.
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
Run Code Online (Sandbox Code Playgroud)
但我不喜欢每次检查都有这么大的代码,并希望将它委托给我的实用程序类中的方法.
if (Utils.hasMapLocationPermissions(getActivity())) {
mMap.setMyLocationEnabled(true);
}
Run Code Online (Sandbox Code Playgroud)
但是setMyLocationEnabled有注释@RequiresPermission因此我不能将它委托给一个方法,因为lint和editor将它显示为一个错误.
是否有一些注释要写在我的实用工具方法上并抑制lint?
像这样的东西
@ChecksPermission
public boolean hasMapLocationPermissions(Activity activity) {
return // my checking logic..
}
Run Code Online (Sandbox Code Playgroud) 我对 android M 及更高版本的新权限模型有点好奇,尤其是“shouldShowRequestPermissionRationale()”方法。在文档中:
为了帮助查找用户可能需要解释的情况,Android 提供了一个实用方法 shouldShowRequestPermissionRationale()。如果应用程序先前已请求此权限并且用户拒绝了该请求,则此方法返回 true。
注意:如果用户过去拒绝了权限请求并在权限请求系统对话框中选择了不再询问选项,则此方法返回 false。如果设备策略禁止应用拥有该权限,该方法也会返回 false。
好的,用户肯定拒绝了权限。现在在同一页面的代码片段中:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the …Run Code Online (Sandbox Code Playgroud)