为什么FusedLocationProvider.getLocationAvailability()返回null(而不应该返回null)?

4

我这样初始化我的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连接...

2个回答

1
根据文档: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLocationAvailability(com.google.android.gms.common.api.GoogleApiClient)
请注意,即使此方法返回 true(例如,在调用之间禁用了位置设置),getLastLocation(GoogleApiClient) 仍可能返回 null。
因此,您可能会收到 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)

1

您还有这个问题吗?在我的应用程序中运行良好(在Moto X 2013上进行了测试),使用Google Play服务库Rev 25。

但是,当我在已安装Google应用程序的Genymotion模拟器上进行测试时,我得到了null。我必须打开一些Google应用程序,如Google Maps,以更新Google Play服务。之后它就正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接