Android access Android Wear Data layer Api -- synchronize Data Items
Data Items is a Data interface used to synchronize mobile phones and wear. A Date Items usually includes the following parts:
Payload
In a byte array, you can set any data type required to allow Object serialization and deserialization. The size cannot exceed 100 kb.
Path
A unique string, which must start with a forward slash (for example, "/path/to/data ")
Generally, you do not need to implement DataItem directly. You only need:
1. Create a PutDataRequest object and specify a path string to distinguish this item
2. Call setData () to set payload
3. Call DataApi. putDataItem () and request the system to create a data item
4. When a data item is requested, the system returns a data item object that correctly implements the interface.
Use setData () to use the original bytes. We recommend that you use a data map to expose a bundle-like data that is easy to use.
Use Data Map to synchronize Data
If you can use the DataMap class, you can use data items similar to Bundle, and enable serialization and deserialization to help you complete the operation. You can use key-value pairs for data operations.
Steps for using data map
1. Create a PutDataMapRequest object and set the data item path.
2 callPutDataMapRequest. getDataMap () to create a data map. You can set the data
3. Set the required data using the put... () method, as shown in figureputString()
4. CallPutDataMapRequest. asPutDataRequest () CreationPutDataRequest object
5 callDataApi.putDataItem()
Request the system to create a data item
If the mobile phone is not connected to wear, the cache will wait until the connection is synchronized.
The following code is used:
PutDataMapRequest dataMap = PutDataMapRequest.create("/count");dataMap.getDataMap().putInt(COUNT_KEY, count++);PutDataRequest request = dataMap.asPutDataRequest();PendingResult
pendingResult = Wearable.DataApi .putDataItem(mGoogleApiClient, request);
Time when the Data Item is monitored
If one data layer changes the data item, you may need to notify any changed data connections. You can implement these events that listen to the data item through time. The following is an example.
@Overridepublic void onDataChanged(DataEventBuffer dataEvents) { for (DataEvent event : dataEvents) { if (event.getType() == DataEvent.TYPE_DELETED) { Log.d(TAG, "DataItem deleted: " + event.getDataItem().getUri()); } else if (event.getType() == DataEvent.TYPE_CHANGED) { Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri()); } }}