GoogleApiClient尚未连接异常

Rok*_*ndy 5 java android google-play-services

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

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

有时这个错误:

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

即使该onConnected()函数被调用.我把调用buildGoogleApiClient() 转到了onCreate()这里的开头是我的代码:

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

调用方法onCreate():

    loc = new MyLocation(MainActivity.this);
    if (loc.checkPlayServices()) {
        loc.buildGoogleApiClient();
        loc.createLocationRequest();
    }
Run Code Online (Sandbox Code Playgroud)

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

cgr*_*cgr 0

您不应loc.createLocationRequest();在调用后立即调用loc.buildGoogleApiClient();,而是调用 loc.createLocationRequest()ApiCLient onConected()loc.createLocationRequest()要求 GoogleApiClient 在调用时已连接。

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