Android 可穿戴设备:如何处理已连接设备的事件?

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

我想从智能手表拦截与智能手机的连接事件。这是由 Android 和 Android Wear 自动管理的,所以我需要从手表上的应用程序 运行 获取此事件。

我在 WearableAPI 上发现无需轮询即可收到通知 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
  }
}

这样做对吗?那么这是一个正常的服务吗?我必须启动它还是在后台自动 运行? 还有其他方法可以执行此任务吗?

这是reference

要在可穿戴设备和手持应用程序之间交换数据,我强烈建议您使用 Wearable.DataApiWearable.MessageApi。您可能希望在双方都有 WearableListenerService 运行 的子 class,并处理通信 onDataChanged/onMessageReceived。他们在 super class 上有一个空的实现。所以你必须覆盖你需要的那个。如果您使用 DataApi,则必须覆盖 onDataChanged,否则 onMessageReceived

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

你必须在清单中声明你的子class,并使用BIND_LISTENER作为动作,

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

Android 负责剩下的事情。