我正在使用Google位置API在地图上显示用户位置。
当应用首次加载时,会显示基本原理对话框,说明用户需要启用位置访问权限的原因。然后,系统会显示runtime permission dialog
,用户点击“允许”即可启用位置访问权限。然后地图加载正常,没有任何崩溃。
但是,当应用程序恢复时(进入后台后),由于用户已授予位置访问权限,因此不会显示任何基本原理对话框。在此方案中,仅显示runtime permission dialog
。现在,如果用户点击“拒绝”,则应用会崩溃。此代码在M(M> Lollipop,Jellybean,KitKat等。)下的Android版本中运行良好。
有没有办法在此阶段处理运行时异常?
错误是:
java.lang.SecurityException:客户端必须具有ACCESS_FINE_LOCATION 请求PRIORITY_HIGH_ACCURACY位置的权限。
我正在使用标准的Sample MyLocation演示应用,没有任何第三方库:
我也尝试过使用PermissionsDispatcher Library,但是同样的错误仍然存在。
PermissionDispatcher Android-Google-Maps-Demo
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
非常感谢任何帮助。
答案 0 :(得分:0)
确保您在Manifest文件中添加了关于您正在询问和确切需要的权限的权限
您的代码可能有问题。 试试这个图书馆:RuntimePermission Library 要手动询问许可。
答案 1 :(得分:0)
从Android 6.0(API级别23)开始,用户grant permissions在应用运行时应用于应用,而不是在他们安装应用时。此方法简化了应用安装过程,因为用户在安装或更新应用时无需授予权限。它还使用户可以更好地控制应用程序的功能。
如何检查您是否拥有该权限:
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
How to request the permissions you need :
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
如何访问请求的结果:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the task you need to do.
} else {
// permission denied, boo! Disable the functionality that depends on this permission.
}
return;
}
}
}