Handle Data Layer events on Wear

When you make a call to the Data Layer API, you can receive the status of the call when it completes. You also can listen for data events, resulting from data changes that your app makes anywhere on the Wear OS by Google network.

Note: A Wear app can communicate with a phone app using the Data Layer API, but connecting to a network using this API is discouraged.

Refer to the following related resources:

Wait for the status of Data Layer calls

Calls to the Data Layer API, for example, a call using the putDataItem method of the DataClient class, sometimes return a Task<ResultType> object. As soon as the Task object is created, the operation is queued in the background. If you do nothing more after this, the operation eventually completes silently. However, you'll usually want to do something with the result after the operation completes, so the Task object lets you wait for the result status, either synchronously or asynchronously.

Asynchronous calls

If your code is running on the main UI thread, do not make blocking calls to the Data Layer API. You can run the calls asynchronously by adding a callback method to the Task object, which fires when the operation is completed:

// Using Java 8 Lambdas.
task.addOnSuccessListener(dataItem -> handleDataItem(dataItem));
task.addOnFailureListener(dataItem -> handleDataItemError(dataItem));
task.addOnCompleteListener(task -> handleTaskComplete(task));

See the Task API for other possibilities, including the ability to chain the execution of different tasks together.

Synchronous calls

If your code is running on a separate handler thread in a background service (which is the case in a WearableListenerService), it's fine for the calls to block. In this case, you can call Tasks.await() on the Task object, which blocks until the request completes and returns a Result object:

try {
    DataItemResult result = Tasks.await(dataItemTask);
    Log.d(TAG, "Data item set: " + result.getDataItem().getUri());
} catch (ExecutionException | InterruptedException e) {
  ...
}

Listen for Data Layer events

Because the data layer synchronizes and sends data across the handheld and wearable, it is usually necessary to listen for important events. Examples of such events include creation of data items and receipt of messages.

To listen for data layer events, you have two options:

With both of these options, you override the data event callback methods for the events you are interested in handling.

Note: Regarding battery usage, a WearableListenerService is registered in an app's manifest and can launch the app if it is not already running. If you only need to listen for events when your app is already running, which is often the case with interactive applications, then do not use a WearableListenerService. Instead register a live listener using, for example, the addListener method of the DataClient class. This can reduce the load on the system and reduce battery usage.

With a WearableListenerService

You typically create instances of this service in both your wearable and handheld apps. If you are not interested in data events in one of these apps, then you don't need to implement this service in that particular app.

For example, you can have a handheld app that sets and gets data item objects and a wearable app that listens for these updates to update its UI. The wearable never updates any of the data items, so the handheld app doesn't listen for any data events from the wearable app.

Some of the events you can listen for using WearableListenerService are as follows:

  • onDataChanged(): Whenever a data item object is created, deleted, or changed, the system triggers this callback on all connected nodes.
  • onMessageReceived(): A message sent from a node triggers this callback on the target node.
  • onCapabilityChanged(): When a capability that an instance of your app advertises becomes available on the network, that event triggers this callback. If you're looking for a nearby node you can query the isNearby() method of the nodes provided in the callback.

In addition to those on this list, you can listen for events from ChannelClient.ChannelCallback, such as onChannelOpened().

All of the above events are executed in a background thread, not on the main thread.

To create a WearableListenerService, follow these steps:

  1. Create a class that extends WearableListenerService.
  2. Listen for the events that you're interested in, such as onDataChanged().
  3. Declare an intent filter in your Android manifest to notify the system about your WearableListenerService. This declaration allows the system to bind your service as needed.

The following example shows how to implement a simple WearableListenerService:

public class DataLayerListenerService extends WearableListenerService {
    private static final String TAG = "DataLayerSample";
    private static final String START_ACTIVITY_PATH = "/start-activity";
    private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";

    @Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "onDataChanged: " + dataEvents);
        }

        // Loop through the events and send a message
        // to the node that created the data item.
        for (DataEvent event : dataEvents) {
            Uri uri = event.getDataItem().getUri();

            // Get the node id from the host value of the URI
            String nodeId = uri.getHost();
            // Set the data of the message to be the bytes of the URI
            byte[] payload = uri.toString().getBytes();

            // Send the RPC
            Wearable.getMessageClient(context).sendMessage(
                  nodeId,  DATA_ITEM_RECEIVED_PATH, payload);
        }
    }
}

The next section explains how to use an intent filter with this listener.

Use filters with WearableListenerService

An intent filter for the WearableListenerService example shown in the previous section might look like this:

<service android:name=".DataLayerListenerService">
  <intent-filter>
      <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
      <data android:scheme="wear" android:host="*"
               android:path="/start-activity" />
  </intent-filter>
</service>

In this filter, the DATA_CHANGED action replaces the previously recommended BIND_LISTENER action so that only specific events wake or launch your app. This change improves system efficiency and reduces battery consumption and other overhead associated with your app. In this example, the watch listens for the /start-activity data item, and the phone listens for the /data-item-received message response.

Standard Android filter matching rules apply. You can specify multiple services per manifest, multiple intent filters per service, multiple actions per filter, and multiple data stanzas per filter. Filters can match on a wildcard host or on a specific one. To match on a wildcard host, use host="*". To match on a specific host, specify host=<node_id>.

You can also match a literal path or path prefix. If you are matching by path or path prefix, you must specify a wildcard or specific host. If you do not do so, the system ignores the path you specified.

For more information on the filter types that Wear supports, see the API reference documentation for WearableListenerService.

For more information on data filters and matching rules, see the API reference documentation for the data manifest element.

When matching intent filters, there are two important rules to remember:

  • If a scheme is not specified for the intent filter, the system ignores all the other URI attributes.
  • If no host is specified for the filter, the system ignores all the path attributes.

With a live listener

If your app only cares about data-layer events when the user is interacting with the app, it may not need a long-running service to handle every data change. In such a case, you can listen for events in an activity by implementing one or more of the following interfaces:

To create an activity that listens for data events:

  1. Implement the desired interfaces.
  2. In the onCreate() or onResume() method, call Wearable.getDataClient(this).addListener(), MessageClient.addListener(), CapabilityClient.addListener(), or ChannelClient.registerChannelCallback() to notify Google Play services that your activity is interested in listening for data layer events.
  3. In onStop() or onPause(), unregister any listeners with DataClient.removeListener(), MessageClient.removeListener(), CapabilityClient.removeListener(), or ChannelClient.unregisterChannelCallback().
  4. If an activity is only interested in events with a specific path prefix, you can add a listener with a suitable prefix filter to only receive data that is relevant to the current application state.
  5. Implement onDataChanged(), onMessageReceived(), onCapabilityChanged(), or methods from ChannelClient.ChannelCallback, depending on the interfaces that you implemented. These methods are called on the main thread, or you can specify a custom Looper using WearableOptions.

Here's an example that implements DataClient.OnDataChangedListener:

public class MainActivity extends Activity implements DataClient.OnDataChangedListener {

    @Override
    public void onResume() {
        Wearable.getDataClient().addListener(this);
    }

    @Override
    protected void onPause() {
        Wearable.getDataClient().removeListener(this);
    }

    @Override
    public 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());
            }
        }
    }
}

Use filters with live listeners

As noted earlier on this page, just as you can specify intent filters for manifest-based WearableListenerService objects, you can use intent filters when registering a live listener through the Wearable API. The same rules are applicable to both API-based live listeners manifest-based listeners.

A common pattern is to register a listener with a specific path or path prefix in an activity’s onResume() method, and to remove the listener in the activity’s onPause() method. Implementing listeners in this fashion allows your app to more selectively receive events, improving its design and efficiency.