user2302078 user2302078 - 2 months ago 18
Android Question

WearableListenerService only handles onMessageReceived() on second try

I've got a simple Android Wear demo to illustrate the Message API. I'm capturing input on a watch and passing it off to a handheld device for cloud processing, so the following class that extends WearableListenerService is running on a phone:

public class ListenerService extends WearableListenerService {

private static final String MESSAGE_PATH = "/handle-inbound-message";

@Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
if(messageEvent.getPath().equals(MESSAGE_PATH)) {
updateData(new String(messageEvent.getData()));
}
}

private void updateData(final String volume) {
new Thread(new Runnable() {
@Override
public void run() {
// do neat stuff with the inbound data
}
}).start();
}
}


...and the wearable code generating the message, by way of clicking a button on the wearable app, is like so:

private void sendToHandheld(final byte[] volume) {
if(nodeId != null) {
new Thread(new Runnable() {
@Override
public void run() {
client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE_PATH, volume);
client.disconnect();
}
}).start();
}
}


The code works fine...except for the fact that I have to click the button twice in the wearable app to get onMessageReceived() to fire. The app starts up, but doesn't get the message the first time...with the app still open, I click the button again and it fires perfectly. Can anyone see where I might have made a mistake?

(Also, I'm seeing a lot of code demos a repos where people don't call super.onMessageReceived().)

Answer

OK, I think I solved the issue - I commented-out the line in onMessageReceived() where the superclass is called...and that fixed it.

SUCCESS!