我有一个手表面,我正在寻找发送使用数据层的几个字符串。我遵循guide,将服务添加到清单并创建了DataLayerListenerService类。
我应该怎么做才能将数据从服务发送到可穿戴设备?在我的配置活动中使用PutDataRequest之前,我已经做到了这一点,它是有效的。现在,我想定期向可穿戴设备发送电池状态、天气信息等信息。我该怎么做呢?
这是到目前为止我的类:
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);
}
}
}发布于 2016-07-25 07:23:05
首先,当您想要连接到Google Play服务库中提供的Google API之一时,创建一个GoogleApiClient实例。您需要创建一个GoogleApiClient实例("Google API客户端“)。Google API客户端为所有Google Play服务提供了一个公共入口点,并管理用户设备和每个Google服务之间的网络连接。
定义一个接收message的WearableListenerService。它从其他节点接收事件,例如数据更改、消息或连接事件。
通过MessageApi发送消息,消息被传递到连接的网络节点。多个可穿戴设备可以连接到用户的手持设备。网络中连接的每个设备都被视为一个节点。对于多个连接的设备,您必须考虑哪些节点接收消息。
然后实现与addListener(GoogleApiClient, MessageApi.MessageListener)一起使用的MessageApi.MessageListener来接收消息事件。希望在后台获得事件通知的调用者应该使用WearableListenerService。然后,接收消息并使用LocalBroadcastManager详细说明该消息,并在佩戴上显示该值。
这里有一个相关的SO标签:Send message from wearable to phone and then immediately reply
https://stackoverflow.com/questions/38545124
复制相似问题