GoogleApiClient尚未连接exception

我正在处理的应用程序,有时可以正常工作,但有时候它会给我这个错误

致命exception:java.lang.RuntimeException:无法暂停活动{com.example.dell.locationapi / com.example.dell.locationapi.MainActivity}:java.lang.IllegalStateException:GoogleApiClient尚未连接。

有时这个错误:

java.lang.IllegalStateException:GoogleApiClient尚未连接。

即使调用了onConnected()函数。 我将buildGoogleApiClient()的调用移到了onCreate()buildGoogleApiClient() ,这里是我的代码:

 protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API).build(); } 

调用onCreate()的方法:

  loc = new MyLocation(MainActivity.this); if (loc.checkPlayServices()) { loc.buildGoogleApiClient(); loc.createLocationRequest(); } 

但它有时会一直给出同样的错误,不知道为什么会发生这种情况?!

你不应该调用loc.createLocationRequest(); 调用loc.buildGoogleApiClient()后立即执行; 而是在ApiCLient的onConected()中调用loc.createLocationRequest()。 loc.createLocationRequest()要求GoogleApiClient在调用时连接。

就此而言,您应该调用任何需要在onConnected()中连接APiCLient的API。 这样,您可以在使用ApiClient时避免连接exception。

这种情况来得晚,但无论对谁有用:

  1. 移动loc.buildGoogleApiClient(); 到onCreate方法。
  2. 移动loc.createLocationRequest(); 到onConnected方法。