通过 WearableListenerService 从 Phone 向 Wearable 发送数据

Send Data to Wearable from Phone via WearableListenerService

我有一个表盘,我希望使用数据层发送一些字符串。我按照 guide 将服务添加到清单并创建 DataLayerListenerService class.

我应该怎么做才能从服务向可穿戴设备发送数据?在我的配置 activity 中使用 PutDataRequest 之前,我已经这样做了。我现在想定期向可穿戴设备发送电池统计信息、天气信息等。我该怎么做?

这是我的 Class 到目前为止:

public class DataLayerListenerService extends WearableListenerService {

private static final String TAG = DataLayerListenerService.class.getSimpleName();
public static final String EXTRAS_PATH = "/extras";
private static final String START_ACTIVITY_PATH = "/start-activity";
private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";
private GoogleApiClient mGoogleApiClient;

public static void LOGD(final String tag, String message) {
    if (Log.isLoggable(tag, Log.DEBUG)) {
        Log.d(tag, message);
    }
}

@Override
public void onCreate() {
    super.onCreate();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    LOGD(TAG, "onDataChanged: " + dataEvents);
    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
        ConnectionResult connectionResult = mGoogleApiClient
                .blockingConnect(30, TimeUnit.SECONDS);
        if (!connectionResult.isSuccess()) {
            Log.e(TAG, "DataLayerListenerService failed to connect to GoogleApiClient, "
                    + "error code: " + connectionResult.getErrorCode());
            return;
        }
    }

    // Loop through the events and send a message back to the node that created the data item.
    for (DataEvent event : dataEvents) {
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();
        if (EXTRAS_PATH.equals(path)) {
            // Get the node id of the node that created the data item from the host portion 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.MessageApi.sendMessage(mGoogleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH,
                    payload);
        }
    }
}

首先,创建一个 GoogleApiClient 的实例,当您想要连接到 Google Play 服务库中提供的 Google API 之一时.您需要创建 GoogleApiClient ("Google API Client") 的实例。 Google API 客户端为所有 Google Play 服务提供一个公共入口点,并管理用户设备与每个 Google 服务之间的网络连接。

定义一个WearableListenerService which receives the message。它从其他节点接收事件,例如数据更改、消息或连接事件。

通过 MessageApi 发送消息,消息将传送到连接的网络节点。多个可穿戴设备可以连接到用户的手持设备。网络中的每个连接设备都被视为一个节点。对于多个连接的设备,您必须考虑哪些节点接收消息。

然后实现 MessageApi.MessageListeneraddListener(GoogleApiClient, MessageApi.MessageListener) 一起使用来接收消息事件。希望在后台收到事件通知的呼叫者应使用 WearableListenerService。然后,接收消息并使用 LocalBroadcastManager 详细说明消息并在穿戴上显示值。

这是一张相关的 SO 票: