A Guide to the Android Wear Message API

While Android Wear provides a lot of great features, such as notifications, out of the box, its real potential lies in the ability to create native apps that communicate with a paired smartphone. Luckily, Android Wear comes with a few new APIs to help make this communication a lot smoother for developers: the Message API, Node API and DataLayer API. Each of these has their own unique purpose; the Message API is designed for “fire and forget it” types of messages, the DataLayer API supports syncing data between a smartphone and a wearable, and the Node API handles events related to local and connected device nodes.

For this tutorial I’ll cover using the Message API to send data from a smartphone to an Android Wear device. We’ll start a watch activity by using a WearableListenerService and display text in a ListView through the MessageApi.MessageListener interface, though all three APIs are used in a similar way. All sample code for this tutorial can be found on GitHub.

To start, create a project in Android Studio that has both a mobile and wear module:

Once your project and modules are created, you can start building the mobile side of your application. The sample project contains simple ListViewEditText and Button views that allow the user to enter text and, when the Button is pressed, display it in the ListView while also sending that text to the wearable.

To start, open AndroidManifest.xml in the mobile module and add a meta-data tag for Google Play Services

  1. <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Next, we can focus on the mobile MainActivity class. The first thing we need to do is connect the GoogleApiClient and implement the GoogleApiClient.ConnectionCallbacks interface:

  1. private void initGoogleApiClient() {
  2.     mApiClient = new GoogleApiClient.Builder( this )
  3.             .addApi( Wearable.API )
  4.             .build();
  6.     mApiClient.connect();
  7. }

When the GoogleApiClient has finished connecting, onConnected will be called. When it is, we’ll send a message through the Message API to a WearableListenerService (implemented later in this tutorial) running on the Wear in order to start our watch activity.

  1. @Override
  2. public void onConnected(Bundle bundle) {
  3.     sendMessage( START_ACTIVITY, "" );
  4. }

…where START_ACTIVITY is a string value that must begin with /, denoting a message path.

  1. private static final String START_ACTIVITY = "/start_activity";

Aside from our initial message, we also want a message to be sent when our ‘send’ button is pressed. This is done through a simple OnClickListener that uses a different path value of /message and sends the text present in the EditText at the bottom of the screen.

  1.     mSendButton.setOnClickListener( new View.OnClickListener() {
  2.         @Override
  3.         public void onClick( View view ) {
  4.             String text = mEditText.getText().toString();
  5.             if ( !TextUtils.isEmpty( text ) ) {
  6.                 mAdapter.add( text );
  7.                 mAdapter.notifyDataSetChanged();
  9.                 sendMessage( WEAR_MESSAGE_PATH, text );
  10.             }
  11.         }
  12.     });

The sendMessage method is where we really start to see how we interact with the new Android Wear APIs. In order to send a message to the Wear, we must first use the Node API to get a list of nodes connected to the device. Once we have this list, we send a message to each node using MessageAPI with references to the GoogleApiClient, node ID, the path used to determine the type of message being sent, and the message payload as a byte array. A MessageApi.SendMessageResult is returned that can be used to determine if a message was successfully sent to the current node. Once the message is sent, we clear the EditText view to allow the user to enter more text.

  1.     private void sendMessage( final String path, final String text ) {
  2.     new Thread( new Runnable() {
  3.         @Override
  4.         public void run() {
  5.             NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mApiClient ).await();
  6.             for(Node node : nodes.getNodes()) {
  7.                 MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
  8.                         mApiClient, node.getId(), path, text.getBytes() ).await();
  9.             }
  11.             runOnUiThread( new Runnable() {
  12.                 @Override
  13.                 public void run() {
  14.                     mEditText.setText( "" );
  15.                 }
  16.             });
  17.         }
  18.     }).start();
  19. }

Finally in onDestroy, we need to disconnect from GoogleApiClient.

  1. @Override
  2. protected void onDestroy() {
  3.     super.onDestroy();
  4.     mApiClient.disconnect();
  5. }

Now that the mobile MainActivity is ready, it’s time to move into the wear module. First we’ll want to create a class that extends from WearableListenerService, which is a service that implements the three Wear communication APIs. For our purposes we only need to override the onMessageReceived method. In this method we check the path that was sent over the MessageApi to determine the type of message, and then, if appropriate, fire off an intent to our wear MainActivity to bring our application to the forefront.

  1. private static final String START_ACTIVITY = "/start_activity";
  3. @Override
  4. public void onMessageReceived(MessageEvent messageEvent) {
  5.     if( messageEvent.getPath().equalsIgnoreCase( START_ACTIVITY ) ) {
  6.         Intent intent = new Intent( this, MainActivity.class );
  7.         intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
  8.         startActivity( intent );
  9.     } else {
  10.         super.onMessageReceived( messageEvent );
  11.     }
  12. }

Once we’re done implementing our service, we need to add it into the wear AndroidManifest.xmlfile.

  1.     <service android:name=".WearMessageListenerService">
  2.         <intent-filter>
  3.             <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
  4.         </intent-filter>
  5.     </service>

As mentioned earlier, there are two ways to receive a message on Android Wear. The next way is implementing MessageApi.MessageListener in our Wear MainActivity. To start, we need to connect GoogleApiClient in the same way as our mobile application. In the onConnectedcallback, we add our wearable listener to the api client

  1. @Override
  2. public void onConnected( Bundle bundle ) {
  3.     Wearable.MessageApi.addListener( mApiClient, this );
  4. }

Next, we simply override the onMessageReceived method from the MessageListener interface, check the path value to determine if we want to take action, and then add the payload text to our adapter to display the text in our wear ListView

  1. @Override
  2. public void onMessageReceived( final MessageEvent messageEvent ) {
  3.     runOnUiThread( new Runnable() {
  4.         @Override
  5.         public void run() {
  6.             if( messageEvent.getPath().equalsIgnoreCase( WEAR_MESSAGE_PATH ) ) {
  7.                 mAdapter.add( new String( messageEvent.getData() ) );
  8.                 mAdapter.notifyDataSetChanged();
  9.             }
  10.         }
  11.     });
  12. }

This will display the text from our mobile app on the wearable, as seen below (the screen shot was taken from a Moto 360, hence the cut off portion at the bottom).

And with that we now have a working communication channel from a smartphone to a paired Android Wear device. I hope this tutorial helps you build your own applications. Good luck!

Author: Paul Trebilcox-Ruiz