Android Wear开发 - 数据通讯 - 第一节 : 连接数据层

http://developer.android.com/training/wearables/data-layer/accessing.html

Accessing the Wearable Data Layer-数据层连接

GoogleApiClient是一个用于整合所有谷歌服务的入口,想要连接数据层,需要构建一个对象.
GoogleApiClient提供了一个builder方法简化了构建对象的步骤.

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
// Now you can use the 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);
if (result.getErrorCode() == ConnectionResult.API_UNAVAILABLE) {
// The Android Wear app is not installed
}
}
})
// Request access only to the Wearable API
.addApi(Wearable.API)
.build();

重要提示:当一个设备没有安装"Android Wear",那么GoogleApiClient则会返回连接失败,回调onConnectionFailed这个方法,错误码为ConnectionResult.API_UNAVAILABLE.此时若想要保持其他谷歌服务正常使用,应当将连接Wear API的GoogleApiClient对象与其他服务的对象独立开来.

在调用了GoogleApiClient的connect()方法后就会尝试着去连接服务,在连接成功后会回调onConnected(),在这个方法里,我们就可以调用数据层API.

上一篇:HDU 4821 String(BKDRHash)


下一篇:24个 HTML5 & CSS3 下拉菜单效果及制作教程