How do I implement a request-response protocol for an Android Wear 2.0 app?
Scenario:
When I tap on a button on the watch, I want it to fetch some data from the phone and display it on the watch's screen.
What I tried:
I implemented a working example using the MessageApi
, but I don't like it. I send a dummy "request" in one place using one method, I disregard the PendingResult
and then hope that eventually I will receive a message that will be a corresponding response.
Ideally, what I'd like to have is:
byte[] responseBytes = sendRequest(someRequestBytes);
I'm not sure what you have tried.
But this code should work to send a byte array.
Wearable.MessageApi.sendMessage(googleApiClient, transcriptionNodeId,
VOICE_TRANSCRIPTION_MESSAGE_PATH, voiceData).setResultCallback(
new ResultCallback() {
@Override
public void onResult(SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
// Failed to send message
}
}
}
);
voiceData is a simple byte array. This array will be received by both wearable and handheld device.
https://developer.android.com/training/wearables/data-layer/messages.html
To retrieve the data use this:
@Override
public void onMessageReceived(MessageEvent messageEvent) {
if (messageEvent.getPath().equals(YOUR_TEXT)) {
messageEvent.getData();//this is your byte array
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.