【问题标题】:Why does FusedLoactionProvider.getLocationAvailability() return null (while it should not)?为什么 FusedLoactionProvider.getLocationAvailability() 返回 null (虽然它不应该)?
【发布时间】:2018-12-14 15:30:32
【问题描述】:

像这样启动我的谷歌播放服务客户端:

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 连接存在...

【问题讨论】:

    标签: android google-play-services


    【解决方案1】:

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

    请注意,getLastLocation(GoogleApiClient) 始终可以 即使此方法返回 true(例如位置设置),也返回 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)
    

    【讨论】:

      【解决方案2】:

      你还有这个问题吗?它在我的应用程序中运行良好(在 Moto X 2013 上测试)与 Google Play Service Libary Rev 25

      但是当我在已经安装了 Google Apps 的 Genymotion 模拟器上进行测试时,我得到了null。我必须打开一些像谷歌地图这样的谷歌应用来更新谷歌播放服务。之后它工作正常。

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 1970-01-01
        • 2022-01-20
        • 2013-01-14
        • 1970-01-01
        • 2019-08-21
        • 2021-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多