Search code examples
androidlistenerwear-osandroid-wear-data-api

Send data and wait for the answers with the Wearable Data Layer API


I have a wearable device from which data is sent to a handheld device wrapped in a DataMap object. On the handheld device I implemented a listener service that extends WearableListenerService implemented in this way:

public class ListenerService extends WearableListenerService {
    private static final String TAG = ListenerService.class.toString();

    private static final String WEARABLE_DATA_PATH = "/wearable_data";

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        DataMap dataMap;

        for (DataEvent event : dataEvents) {
            if (event.getType() == DataEvent.TYPE_CHANGED) {
                String path = event.getDataItem().getUri().getPath();

                if (path.equals(WEARABLE_DATA_PATH)) {
                    dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();

                    messageReceived(dataMap);
                }
            }
        }
    }

    private void messageReceived(DataMap dataMap) {
        Log.v(TAG, "DataMap received on handheld device: " + dataMap);
    }
}

The transmission from wearable to handheld works flawlessly. However, I would need to send back from handheld to wearable an answer, like "ok done" or "error xxx". How can I do that?


Solution

  • it works the same way. You need a subclass of WearableListenerService on your wearable app, declared it on your AndroidManifest.xml, with the action com.google.android.gms.wearable.BIND_LISTENER. When the handheld is ready send a Message to the Wearable, you can use either the DataApi or the MessageApi and corresponding callback will be invoked on the other endpoint