【发布时间】:2020-06-13 15:59:33
【问题描述】:
我实现了一个使用 GPS 位置的应用程序,因此我正在处理权限问题。 该应用程序运行正常,所有位置都正确执行。 当我安装应用程序时,第一个片段正确打开并向用户显示 GPS 权限请求。 在这之后,我还添加了一个对话框,请求设置 GPS 以启动应用程序。 如果在第一次启动之前(安装后)GPS 设置为关闭,当应用程序启动时,它会在后台显示第一个片段,请求 GPS 权限,然后请求打开 GPS 内部设置。 如果在首次启动之前(安装后)GPS 设置为 ON,当应用程序启动时,它会在后台显示第一个片段,请求 GPS 权限和应用程序崩溃,保持 GPS 权限请求处于活动状态。如果我按 OK,我会重新启动应用程序并且一切正常。 为什么当 GPS 开启设置设置为开启时会出现此问题? 下面是部分代码:
在第一个片段上,onCreateView 我为 GPS 权限编写了以下代码:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
showAlert(getString(R.string.PermessoDisp), getString(R.string.PermessoDispTitle));
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_REQUEST_LOCATION);
}
} else {
}
在 onStart() 我有:
@Override
public void onStart() {
super.onStart();
if (isLocationEnabled()) {
mGoogleApiClient.connect();
} else {
showAlertGPSSettings();
}
}
其中 showAlertGPSSettings() 是要求用户打开 GPS 以使用应用程序的方法。 我也有:
@Override
public void onConnected(@Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(500);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
}
}
当应用程序崩溃时(首次启动时 GPS 设置为 ON),出现以下错误:
java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
错误所在的行,在onConnected方法里面:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
有什么建议吗?
【问题讨论】:
-
"和应用程序崩溃" -- 使用 Logcat 检查与您的崩溃相关的堆栈跟踪:stackoverflow.com/questions/23353173/… 如果您不理解堆栈跟踪告诉您的内容,请编辑您的问题并提供完整的堆栈跟踪。
-
感谢 CommonsWare,如果您在我上面的文字中看到我在最后写的错误
-
对不起,我正在寻找完整的堆栈跟踪(我建议您在发生崩溃时始终发布一个)。您的权限逻辑有点错误。你检查权限......但你仍然创建
GoogleApiClient。然后,即使您没有权限,您也可以在该GoogleApiClient上调用connect(),并且即使您没有权限,您也可以在onConnected()中尝试使用位置。更改您的GoogleApiClient逻辑,以便您仅在您有权限时创建并连接到它,或者因为您从权限开始,或者您被称为onRequestPermissionsResult()。
标签: java android permissions gps location