Search code examples
androidevent-handlingconnectionwear-osandroid-wear-data-api

Android wearables: How to handle the event of a connected device?


From the smartwatch I'd like to intercept the event of the connection to a smartphone. This is automatically managed by Android and Android Wear so I need to get this event from my app running on the watch.

I found out this on WearableAPI to be notified without polling Wearable.NodeApi.getConnectedNodes

public class MyService extends WearableListenerService {
  @Override
  public void onPeerConnected(Node peer) {
    Log.i("my wear service", "connected");
    super.onPeerConnected(peer);
    // here I would use MessageAPI to send data saved on "disk" to the smartphone
  }
}

Is it the right way? So is this a normal Service? Do I have to start it or is it automatically running in background? Are there any other ways to perform this task?

this is the reference


Solution

  • to exchange data between the wearable and the handheld app I strongly suggest you to use the Wearable.DataApi or the Wearable.MessageApi. You will probably want to to have a subclass of WearableListenerService running on both side, and handling the communication onDataChanged/onMessageReceived. They have an empty implementation on the super class. So you have to override the one you need. If you use the DataApi you'll have to override onDataChanged, onMessageReceived otherwise.

    Do I have to start it or is it automatically running in background

    you have to declare your subclass in the manifest, and use BIND_LISTENER as action,

    <intent-filter>
       <action android:name="com.google.android.gms.wearable.BIND_LISTENER"/>
    </intent-filter>
    

    Android takes care of the rest.