
Android Wear Docs, Release 1.1
}
// Data layer and lifecycle implementation (Step 2)
...
}
2. Add callback methods for the data layer and lifecycle events. For simplicity, send a message in the onConnected
callback method.
// Connect to the data layer when the Activity starts
@Override
protected void onStart() {
super.onStart();
googleClient.connect();
}
// Send a message when the data layer connection is successful.
@Override
public void onConnected(Bundle connectionHint) {
String message = "Hello wearable\n Via the data layer";
//Requires a new thread to avoid blocking the UI
new SendToDataLayerThread("/message_path", message).start();
}
// Disconnect from the data layer when the Activity stops
@Override
protected void onStop() {
if (null != googleClient && googleClient.isConnected()) {
googleClient.disconnect();
}
super.onStop();
}
// Placeholders for required connection callbacks
@Override
public void onConnectionSuspended(int cause) { }
@Override
public void onConnectionFailed(ConnectionResult connectionResult) { }
3. Define a class that extends the Thread class and implements a method that sends your message to all nodes
currently connected to the data layer. This task can block the main UI thread, so it must run in a new thread.
class SendToDataLayerThread extends Thread {
String path;
String message;
// Constructor to send a message to the data layer
SendToDataLayerThread(String p, String msg) {
path = p;
message = msg;
}
public void run() {
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleClient).await();
for (Node node : nodes.getNodes()) {
SendMessageResult result = Wearable.MessageApi.sendMessage(googleClient, node.getId(), path, message.getBytes()).await();
if (result.getStatus().isSuccess()) {
Log.v("myTag", "Message: {" + message + "} sent to: " + node.getDisplayName());
}
6.1. First Wearable Message 27
Comentarios a estos manuales