以下内容翻译自android wear的官方教程,本人水平有限,如有错误欢迎指出
home
以下正文
为了访问数据层的API,需要创建 GoogleApiClient
的实例,这也是所有google play services API的入口点。
GoogleApiClient
提供一个builder来更容易的创建一个client。一个最小的GoogleApiClient
如下所示:
注意:下面的这个最小的client是可以启动了,但你可能需要实现回调和处理错误情况,你可以查阅 Accessing Google Play services APIs来获得创建GoogleApiClient更多信息。
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
// 从这里开始你可以使用Data Layer API
}
@Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
})
// 请求只能访问Wearable API
.addApi(Wearable.API)
.build();
重要:如果你在 GoogleApiClient
添加多个API,你可能会遇到连接错误。为了避免连接错误,用 [addApiIfAvailable()
](http://developer.android.youdaxue.com/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#addApiIfAvailable(com.google.android.gms.common.api.Api<? extends com.google.android.gms.common.api.Api.ApiOptions.NotRequiredOptions>, com.google.android.gms.common.api.Scope...))方法并表明你的client不会因为API无效而报错,查看 Access the Wearable API获取更多信息
在你使用数据层API之前,用connect()
方法启动一个连接。当系统回调onConnected()方法的时候,就说明连接已经成功,你可以开始使用数据层的API.