Sending and Receiving Messages

This lesson teaches you to

  1. Send a Message
  2. Receive a Message

You send messages using the MessageApi and attach the following items to the message:

  • An arbitrary payload (optional)
  • A path that uniquely identifies the message's action

Unlike with data items, there is no syncing between the handheld and wearable apps. Messages are a one-way communication mechanism that's good for remote procedure calls (RPC), such as sending a message to the wearable to start an activity.

Send a Message

The following example shows how to send a message that indicates to the other side of the connection to start an activity. This call is synchronous and blocks processing until the message is received or until the request times out:

Note: Read more about asynchronous and synchronous calls to Google Play services and when to use each in Communicate with Google Play Services.

Node node; // the connected device to send the message to
GoogleApiClient mGoogleApiClient;
public static final START_ACTIVITY_PATH = "/start/MainActivity";
...

    SendMessageResult result = Wearable.MessageApi.sendMessage(
            mGoogleApiClient, node, START_ACTIVITY_PATH, null).await();
    if (!result.getStatus().isSuccess()) {
        Log.e(TAG, "ERROR: failed to send Message: " + result.getStatus());
    }

Here's a simple way to get a list of connected nodes that you can potentially send messages to:

private Collection<String> getNodes() {
    HashSet <String>results = new HashSet<String>();
    NodeApi.GetConnectedNodesResult nodes =
            Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
    for (Node node : nodes.getNodes()) {
        results.add(node.getId());
    }
    return results;
}

Receive a Message

To be notified of received messages, you implement the MessageListener interface to provide a listener for message events. Then you register your listener with the MessageApi.addListener() method. This example shows how you might implement the listener to check the START_ACTIVITY_PATH that the previous example used to send the message. If this condition is true, a specific activity is started.

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    if (messageEvent.getPath().equals(START_ACTIVITY_PATH)) {
        Intent startIntent = new Intent(this, MainActivity.class);
        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startIntent);
    }
}

This is just a snippet that requires more implementation details. Learn about how to implement a full listener service or activity in Listening for Data Layer Events.