GoogleApiClient检查android上的api可用性

时间:2017-04-10 09:39:36

标签: android google-api-client

在调用connect时,有没有办法在预先使用google api客户端时检查API的可用性?

而不是

GoogleApiClient.Builder apiClientBuilder = new GoogleApiClient.Builder(context);
apiClientBuilder.addApi(API);
apiClientBuilder.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        if (result.isSuccess()) {
        ...
        } else {
            // handle missing api 
        }
                        }
                    });
GoogleApiClient client = apiClientBuilder.build();
client.connect();

我想使用类似的东西:

if (GoogleApiClient.isApiAvailable(API)) {
    GoogleApiClient.Builder apiClientBuilder = new GoogleApiClient.Builder(context);
    apiClientBuilder.addApi(API);
    GoogleApiClient client = apiClientBuilder.build();
    client.connect();
    ...
} else {
  // handle missing api without connecting
}

1 个答案:

答案 0 :(得分:1)

我已使用以下代码检查WearOS

    int result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(ctx);
if(ConnectionResult.SUCCESS == result ) {

    MessageClient mc = Wearable.getMessageClient(ctx);

    try {
        Task<Void> t = GoogleApiAvailability.getInstance().checkApiAvailability(mc);

        t.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void v) {
                //... MessageClient available
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //.. MessageClient not available
            }
        });
    }
    catch (Exception ex) {
        //.. MessageClient not available
    }
}