android Wearable-Accessing the Wearable Data Layer and Syncing Data Items

GoogleApiClient provides a builder that makes it easy to create an instance of the client. A minimal GoogleApiClientlooks like this:

Note: For now, this minimal client is enough to get started. However, see Accessing Google Play services APIs for more information about creating a GoogleApiClient, implementing its callbacks, and handling error cases.

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);
                }
            })
        // Request access only to the Wearable API
        .addApi(Wearable.API)
        .build();

Important: If you are adding multiple APIs to a GoogleApiClient, you may run into client connection errors on devices that do not have the Android Wear app installed. To avoid connection errors, call theaddApiIfAvailable() method and pass in the Wearable API to indicate that your client should gracefully handle the missing API. For more information, see Access the Wearable API.

Before you use the data layer API, start a connection on your client by calling the connect() method, as described in Start a Connection. When the system invokes the onConnected() callback for your client, you're ready to use the Data Layer API.

> Syncing Data Items

DataItem defines the data interface that the system uses to synchronize data between handhelds and wearables. A DataItem generally consists of the following items:

  • Payload - A byte array, which you can set with whatever data you wish, allowing you to do your own object serialization and deserialization. The size of the payload is limited to 100KB.
  • Path - A unique string that must start with a forward slash (for instance, "/path/to/data")

 You normally don't implement DataItem directly. Instead, you:

  1. Create a PutDataRequest object, specifying a string path to uniquely identify the item.
  2. Call setData() to set the payload.
  3. Call DataApi.putDataItem() to request the system to create the data item.
  4. When requesting data items, the system returns objects that properly implement the DataItem interface.

However, instead of working with raw bytes using setData(), we recommend you use a data map, which exposes a data item in an easy-to-use Bundle-like interface.

Sync Data with a Data Map

To use a data map:

  1. Create a PutDataMapRequest object, setting the path of the data item.

    Note: The path string is a unique identifier for the data item that allows you to access it from either side of the connection. The path must begin with a forward slash. If you're using hierarchical data in your app, you should create a path scheme that matches the structure of the data.

  2. Call PutDataMapRequest.getDataMap() to obtain a data map that you can set values on.
  3. Set any desired values for the data map using the put...() methods, such as putString().
  4. Call PutDataMapRequest.asPutDataRequest() to obtain a PutDataRequest object.
  5. Call DataApi.putDataItem() to request the system to create the data item.

    Note: If the handset and wearable devices are disconnected, the data is buffered and synced when the connection is re-established.

The increaseCounter() method in the following example shows how to create a data map and put data in it:

public class MainActivity extends Activity implements
        DataApi.DataListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String COUNT_KEY = "com.example.key.count";

    private GoogleApiClient mGoogleApiClient;
    private int count = 0;

    ...

    // Create a data map and put data in it
    private void increaseCounter() {
        PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");
        putDataMapReq.getDataMap().putInt(COUNT_KEY, count++);
        PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
        PendingResult<DataApi.DataItemResult> pendingResult =
                Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
    }

    ...
}

Listen for Data Item Events

public class MainActivity extends Activity implements
        DataApi.DataListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String COUNT_KEY = "com.example.key.count";

    private GoogleApiClient mGoogleApiClient;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Wearable.DataApi.addListener(mGoogleApiClient, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Wearable.DataApi.removeListener(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        for (DataEvent event : dataEvents) {
            if (event.getType() == DataEvent.TYPE_CHANGED) {
                // DataItem changed
                DataItem item = event.getDataItem();
                if (item.getUri().getPath().compareTo("/count") == 0) {
                    DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                    updateCount(dataMap.getInt(COUNT_KEY));
                }
            } else if (event.getType() == DataEvent.TYPE_DELETED) {
                // DataItem deleted
            }
        }
    }

    // Our method to update the count
    private void updateCount(int c) { ... }

    ...
}

This activity implements the DataItem.DataListener interface. This activity adds itself as a listener for data item events inside the onConnected() method and removes the listener in the onPause() method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值