我正在尝试使用google api获取最后一个已知位置。
我收到错误“呼叫需要可能被拒绝的权限......”
但是,我已经在运行时询问了权限,所以我不知道为什么错误仍然显示...
这就是我所做的:
/** 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);
为什么我仍然会收到错误,我该如何解决?
提前致谢!
答案 0 :(得分:1)
有两种方法可以解决Lint的任何投诉:
更改代码以使Lint满意
告诉Lint不要让你一个人,通常是通过@SuppressLint
注释(虽然在某些情况下有其他选择,例如@TargetApi
)
大多数时候,正确的答案是更改您的代码。因此,例如,如果Lint抱怨您在字符串资源可能更合适的地方使用了字符串,那么正确的答案很可能是创建字符串资源。
Lint总体上相当不错的原因是它的大多数检查都处理单个Java语句。
在您的特定情况下,Lint由单个Java语句(您的getLastKnownLocation()
调用)触发,但还需要检查哪些代码路径可以导致该语句,以及是否您确保为所有这些呼叫路径保留适当的运行时权限。坦率地说,林特并不擅长这一点。结果,这个特别的Lint检查引起了比我喜欢的更多“误报”。
可能有一种方法可以重新组织您的代码,以便Lint感到高兴。但是:
对于今天的Lint和所有未来的Lint版本
结果代码可能会让您更加困惑,即使它对Lint不那么混乱
您的代码可能没问题
@SuppressLint
基本上说“我知道我在做什么,不要抱怨,不要管我”。有时,这是让Lint停止抱怨完全有效代码的唯一方法。
在您的特定情况下,请测试您的代码。如果代码既可以执行,也可以不具有所需的运行时权限,那么代码就可以了,@SuppressLint
是一种有效的方法。