0

This is the event-based code

    Wearable.DataApi.addListener(googleApiClient, new DataApi.DataListener() {
        @Override
        public void onDataChanged(DataEventBuffer dataEvents) {
            Log.i(tag, "on data changed " + dataEvents.toString());
            for (DataEvent event : dataEvents) {
                DataItem item = event.getDataItem();
                String path = item.getUri().getPath();
                if (path.equals(PATH_MAP)) {
                    DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                    String dataValue = dataMap.getString(KEY_DATA);
                }
            }
        }
    }).setResultCallback(new ResultCallbacks<Status>() {
        @Override
        public void onSuccess(@NonNull Status status) {
            Log.i(tag, "success");
        }

        @Override
        public void onFailure(@NonNull Status status) {
            Log.i(tag, "failure");
        }
    });

How to read the dataValue associated to KEY_DATA without using the listener pattern? I need this because sometimes the nodes are not synced even if urgent mode has been set. In particular the onDataChanged callback is called only if there was a change of values.

This is a scenario: a mobile apk has been installed, at startup it writes a value on KEY_DATA item. After a wearable apk installation I set the listener to receive this value but the data changed event is not called, so I need a way to get the current value with an explicit polling.

I know that there is also MessageApi but the problem is the same, if a device is not online the message is lost.

user3290180
  • 4,260
  • 9
  • 42
  • 77

1 Answers1

0

You can retrieve previous values from the DataApi using one of the getDataItems methods documented here: https://developers.google.com/android/reference/com/google/android/gms/wearable/DataApi.html

There are various forms depending on the filtering you'd like the API to do before returning data to you. The simplest form looks like this:

Wearable.DataApi.getDataItems(googleApiClient).setResultCallback(new ResultCallback<DataItemBuffer>() {
    @Override
    public void onResult(@NonNull DataItemBuffer buffer) {
        for (DataItem item : buffer) {
            if (item.getUri().getPath().equals(PATH_MAP)) {
               DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
               String dataValue = dataMap.getString(KEY_DATA);
             }
         }
     }
 });

and will return all DataItems your app has sent to the API. You can access the KEY_DATA value as outlined above.

Jan Z.
  • 6,883
  • 4
  • 23
  • 27
Sterling
  • 6,365
  • 2
  • 32
  • 40