访问可穿戴数据层

编写:wly2014 - 原文: <http://developer.android.com/training/wearables/data-layer/accessing.html>

调用数据层API,需创建一个 GoogleApiClient 实例,所有 Google Play services APIs的主要入口点。

GoogleApiClient 提供了一个易于创建客户端实例的builder。最简单的GoogleApiClient如下:

Note: 目前,此小client仅足以能启动。但是,更多创建GoogleApiClient,实现回调方法和处理错误等内容,详见 Accessing Google Play services APIs。

1. GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
2. .addConnectionCallbacks(new ConnectionCallbacks() {
3. @Override
4. public void onConnected(Bundle connectionHint) {
5. Log.d(TAG, "onConnected: " + connectionHint);
6. // Now you can use the Data Layer API
7. }
8. @Override
9. public void onConnectionSuspended(int cause) {
10. Log.d(TAG, "onConnectionSuspended: " + cause);
11. }
12. })
13. .addOnConnectionFailedListener(new OnConnectionFailedListener() {
14. @Override
15. public void onConnectionFailed(ConnectionResult result) {
16. Log.d(TAG, "onConnectionFailed: " + result);
17. }
18. })
19. // Request access only to the Wearable API
20. .addApi(Wearable.API)
21. .build();

Important: 如果我们添加多个API到一个GoogleApiClient,那么可能会在没有安装Android Wear app 的设备上遇到连接错误。为了连接错误,调用addApiIfAvailable()方法,并以Wearable API为参数传进该方法,从而表明client应该处理缺失的API。更多的信息,请见 Access the Wearable API.

在使用数据层API之前,通过调用connect()方法进行连接,如 Start a Connection 中所述。当系统为我们的客户端调用了onConnected() 方法,我们就可以使用数据层API了。