【问题标题】:android geofencing java.lang.IllegalStateException: GoogleApiClient is not connected yetandroid geofencing java.lang.IllegalStateException: GoogleApiClient 尚未连接
【发布时间】:2017-05-29 16:52:29
【问题描述】:

我在我的应用程序中使用地理围栏。每当我尝试添加地理围栏时,都会出现以下错误。

IllegalStateException: GoogleApiClient is not connected yet

在 AppCompatActivity onCreate 方法中我定义了客户端

/* Create a new google api client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();

在我的 onStart 方法中,我连接到它,确保它不为空

/* Connect to the API client */
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}

但它仍然给出了那个错误。

我的 AppCompatActivity 实现了 OnMapReadyCallback 和 ResultCallback 接口等

我有一个重写的方法

@Override
public void onMapReady(GoogleMap googleMap) {}

onMapReady 方法包含这行代码

LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
        getGeofencingRequest(),
        getGeofencePendingIntent()
).setResultCallback(MapsActivity.this);

我已经定义了 getGeofencingRequest 和 getGeofencingPendingIntent 私有方法并覆盖了 ResultCallback 中的 onResult 方法。

我在这个错误上花费了数小时和数小时,但似乎无法取得进展。应用程序正常执行,直到 AppCompatActivity 启动。 onCreate 正常发生,onStart 也正常发生。

我认为这个错误有两种可能:

  1. onMapReady 方法在 onStart 之前被调用(不太可能)

  2. onStop 方法在 onMapReady 方法可用之前断开客户端的连接

我们将不胜感激。

完整要点的链接如下: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac

【问题讨论】:

  • 我认为第一种可能是你的错误原因。因为把它放在 onStart() 上是个坏主意。
  • @mihir raj 事实并非如此,实际上我试图在连接 google api 客户端之前创建地理围栏。 onMapReady 在调用 onConnected 方法之前正在请求 google api 客户端。所以我将 onMapReady 方法中的所有地理围栏代码移到 onConnected 方法中,它工作正常。

标签: android illegalstateexception geofencing android-geofence location-services


【解决方案1】:

我找到了自己问题的答案。

显然,google API 客户端连接与 Google Map 连接是分开的。 API 客户端专门用于定位服务。

因此,我需要在建立 API 连接后设置地理围栏。

所以我也将我的所有地理围栏代码都移到了 onConnected 中。

@Override
public void onConnected(Bundle savedInstanceState) { }

这解决了问题。

看看更新的要点: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac

【讨论】:

  • 您的解决方案是正确的。调用connect方法()后,只要连接请求完成,就会自动调用onConnected()方法。因此,您必须仅在 onConnected() 方法中编写要完成的任务,否则您将遇到 GoogleApiClient 对象的空指针异常。您可以参考此文档以了解有关 onConnected() 方法的更多信息。链接:developers.google.com/android/reference/com/google/android/gms/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 1970-01-01
相关资源
最近更新 更多