gpt4 book ai didi

android - 为什么 FusedLoactionProvider.getLocationAvailability() 返回 null(虽然它不应该)?

转载 作者:太空宇宙 更新时间:2023-11-03 10:18:36 25 4
gpt4 key购买 nike

像这样启动我的 google play 服务客户端:

public class MyApplication  extends Application implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

protected synchronized GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}


/* GoogleApiClient.ConnectionCallbacks */
@Override
public void onConnected(Bundle bundle) {
Log.v(TAG, "Google play services connected.");
boolean isConnected = mGoogleApiClient.isConnected(); // - this is true
boolean isLocAvailable = LocationServices.FusedLocationApi.getLocationAvailability(mGoogleApiClient).isLocationAvailable();
// this causes NullPointerException because getLocationAvailabality() returns null. WHY ????
.
.
.
}

}

Google Play 服务库版本为 Rev.24。为什么会发生这个空指针事件? Google API 客户端已初始化、已连接,一切都按照文档的要求进行了吗?存在 WiFi 连接...

最佳答案

根据文档:https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLocationAvailability(com.google.android.gms.common.api.GoogleApiClient)

Note it's always possible for getLastLocation(GoogleApiClient) to return null even when this method returns true (e.g. location settings were disabled between calls).

因此,您可能会收到 null 的原因有很多。我的建议是您检查权限,并确保允许位置权限,而不仅仅是检查 GoogleClient 是否已连接以及位置是否可用。您可以使用以下功能。

public static boolean checkAppPermissions(Context context, String... strPermissions) {
for (String permissions : strPermissions) {
if (!FrameworkUtils.isStringEmpty(permissions)) {
int result = ContextCompat.checkSelfPermission(context, permissions);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
}
}
}
return false;
}

你可以这样调用它

checkAppPermissions(mContext, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)

关于android - 为什么 FusedLoactionProvider.getLocationAvailability() 返回 null(虽然它不应该)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30183906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com