我试图使用google api获取最后一个已知位置。Android权限请求错误
我得到的错误“呼叫要求可能被拒绝的权限......”
不过,我已经要求在运行时的权限,所以我不知道为什么错误仍显示...
这里是我做了什么:
/** Value to match on callback of request permissions response */
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
/** GoogleApiClient */
private GoogleApiClient googleApiClient = null;
/** Last known location */
private Location lastLocation = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Create a GoogleApiClient instance
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
if (permissions.length == 1 &&
permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION) {
// ERROR STILL SHOWING HERE!
lastLocation = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
}
} else {
// permission denied, boo!
}
break;
}
default:
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
// NO ERROR HERE, IT'S FINE
lastLocation = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
@Override
public void onConnectionSuspended(int i) {
// do nothing
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and a connection to Google APIs
// could not be established. Display an error message, or handle
// the failure silently
Toast toast = Toast.makeText(this, getText(R.string.google_api_connection_error), Toast.LENGTH_LONG);
toast.show();
}
正如你所看到的,这就是我想做的事:
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
为什么我仍然得到错误,我该如何解决这个问题?
在此先感谢!
如果您在Android Studio Java编辑器中引用消息,那是一个Lint警告,而不是错误。如果您确信所有操作都已正确实施,则应该有一个选项来禁止快速修复菜单中的Lint信息。 – CommonsWare
这不是一个警告,它是一个错误。 (棉绒红色)。它不会让我建立项目 – Tirafesi
“这不是一个警告,它是一个错误(在linter上的红色)” - AFAIK,谷歌只使用红色了。 “而且它不允许我构建项目” - 很可能,您在构建过程中遇到了不同的错误,您需要修复这个错误。这将显示在Gradle Console或其他输出窗格中,而不是Java编辑器。这个特定的消息应该只显示在Java编辑器中,因为它是一个Lint警告,而不是编译错误。您也可以按照我的建议进行操作,并使用快速修复菜单添加相应的“@ SuppressLint”注释。 – CommonsWare