我有一个表盘,我希望使用数据层发送一些字符串。我通过将服务添加到清单并创建DataLayerListenerService
类来跟踪guide。
我应该怎样做才能从服务中向可穿戴设备发送数据?我在配置活动中使用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);
}
}
}
答案 0 :(得分:1)
首先,如果要与Google Play服务库中提供的某个Google API建立连接,请创建GoogleApiClient的实例。您需要创建GoogleApiClient实例(“Google API客户端”)。 Google API客户端提供了所有Google Play服务的通用入口点,并管理用户设备与每个Google服务之间的网络连接。
定义接收WearableListenerService
的message。它接收来自其他节点的事件,例如数据更改,消息或连接事件。
通过MessageApi
发送消息,消息将传递到连接的网络节点。多个可穿戴设备可以连接到用户的手持设备。网络中的每个连接设备都被视为节点。对于多个连接的设备,您必须考虑哪些节点接收消息。
然后实施与addListener(GoogleApiClient, MessageApi.MessageListener)
一起使用的MessageApi.MessageListener
来接收消息事件。希望在后台通知事件的呼叫者应使用WearableListenerService
。然后,接收消息并使用LocalBroadcastManager详细说明消息并显示磨损值。
以下是相关的SO票证:Send message from wearable to phone and then immediately reply