如果用户通过该应用启用了位置权限,然后转到手机的设置并在那里禁用了该权限,我的应用就会崩溃。我尝试通过检查onResume的权限来解决此问题,但似乎无法正确解决。 StackOverflow上的其他解决方案无效。
以下代码在我的onCreate()中运行,并检查位置权限:
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
//check which API users are running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//location permission dialog
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
我的onRequestPermissionsResult():
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getContext(), "The app requires location permissions", Toast.LENGTH_LONG).show();
getActivity().finish();
}
break;
}
}
这是我在同一片段中的onResume()代码:
@Override
public void onResume() {
super.onResume();
updatePermissions();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
public void updatePermissions(){
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// mMap.setMyLocationEnabled(true);
} else {
//check which API users are running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//location permission dialog
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
}
该应用程序因错误而崩溃: java.lang.ArrayIndexOutOfBoundsException:length = 0;在fluo.tuki10.fragments.MapFragment.onRequestPermissionsResult(MapFragment.java:232)处为index = 0
这是行
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
我觉得解决方案是实现更好的onResume(),以便在用户在应用程序外部修改权限后检查权限。不幸的是我的代码不足
答案 0 :(得分:1)
在与没有元素的头部比较之前的建议:
如果(grantResults.length> 0)