在尝试连接之前等待 GoogleAPIClient 加载

Wait for GoogleAPIClient to load before trying to connect

我正在使用 Google 地图 API 构建一个简单的地图应用程序。当我打开应用程序时,它有时会崩溃,因为 GoogleApiClient 尚未连接。我有一些方法 运行 需要连接 API。

如何通过等待 API 连接来防止崩溃?

这是我的一些代码: 已连接:

@Override
public void onConnected(Bundle connectionHint)
{
    // this callback will be invoked when all specified services are connected
    //Must ask for explicit permission
    //ie: Opening settings action in order to change or give permissions
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
        mGoogleClient.connect();

        if (currentLocation != null)
        { 
            currentLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
        } 

        else
        {
           if (mGoogleClient!=null )
           {
               mGoogleClient.connect();
           }

            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleClient, locationRequest, this);

        }
    }
}

获取当前位置:

private void getLocation() {

    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(60 * 1000);
    locationRequest.setFastestInterval(30 * 1000);

    mGoogleClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    if (mGoogleClient != null)
    {
        mGoogleClient.connect();
    }


}

我不确定还需要什么。如果我需要提供更多代码,请告诉我。

编辑:崩溃日志

08-15 17:51:54.692 950-950/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.hensh.fusedmap, PID: 950
                                           java.lang.IllegalStateException: GoogleApiClient is not connected yet.
                                               at com.google.android.gms.common.api.internal.zzh.zzb(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzl.zzb(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source)
                                               at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
                                               at com.hensh.fusedmap.MapsActivity.onConnected(MapsActivity.java:667)
                                               at com.google.android.gms.common.internal.zzk.zzk(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzj.zzi(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzh.zzpx(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzh.onConnected(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzl.onConnected(Unknown Source)
                                               at com.google.android.gms.common.api.internal.zzc.onConnected(Unknown Source)
                                               at com.google.android.gms.common.internal.zzj$zzg.zzqL(Unknown Source)
                                               at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
                                               at com.google.android.gms.common.internal.zzj$zza.zzw(Unknown Source)
                                               at com.google.android.gms.common.internal.zzj$zzc.zzqN(Unknown Source)
                                               at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                               at android.os.Looper.loop(Looper.java:135)
                                               at android.app.ActivityThread.main(ActivityThread.java:5294)
                                               at java.lang.reflect.Method.invoke(Native Method)
                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

您应该将代码片段 mMap.animateCamera... 等放入 onMapLoaded。

Detect when Android v2 maps has loaded

并删除 onConnected 方法中的 mGoogleClient.connect();,因为您不必连接两次(或更多)

不清楚您希望您的应用程序如何运行。如果您希望您的位置显示在地图上并在您移动时更新:

  1. 仅在 onCreate 中实例化 GoogleApiClient 一次。
  2. onResume 中连接 GoogleApiClient
  3. onConnected 中提出您的位置请求
  4. onLocationChanged 中,移动您的地图。

可能值得回顾一下:Fatal Exception: java.lang.IllegalStateException GoogleApiClient is not connected yet

GoogleAPIClient 需要先连接,然后才能尝试使用该服务。所以你在 onConnected 中连接它的调用是错误的。如果您在 onConnected 中,则表示客户端 已连接 。您需要在 activity 的 onCreate 中构建 GoogleAPIClient,最好将其连接到 ActivityonStart 中。

private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.<your-xml>);

    mGoogleApiClient = new GoogleApiClient.Builder(context)
             .addConnectionCallbacks(this)
             .addOnConnectionFailedListener(this)
             .addApi(LocationServices.API)
             .build();
}
public void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

此外,在构建 GoogleAPIClient 时,您还可以将 enableAutoManage() 设置为 connectdisconnect 自动管理,这样您就不必手动执行,正如所解释的 here.

public class LocationActivity implements GoogleApiClient.OnConnectionFailedListener {

    /** Google Services client */
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_activity);
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                 .addConnectionCallbacks(this)
                 .enableAutoManage(this, this)
                 .addApi(LocationServices.API)
                 .build();
}