I'm writing an Android Wear app and I want to make the wear device start an intent on the phone when a button is clicked.
To do this, I've first set up the connection to the GoogleApiClient like this
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
Then on button click the function sendMessage is run. This is the function
private void sendMessage(){
if(mNode != null && googleApiClient != null && googleApiClient.isConnected()){
Wearable.MessageApi.sendMessage(
googleApiClient, mNode.getId(),HELLO_WORLD_WEAR_PATH, null).setResultCallback(
new ResultCallback<MessageApi.SendMessageResult>() {
@Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
if(!sendMessageResult.getStatus().isSuccess()){
Log.e("TAG", "Failed to send message with status code: " + sendMessageResult.getStatus().getStatusCode());
}
else{
Log.e("TAG", "Success");
}
}
}
);
}
else {
Log.e("TAG","No nodes" + mNode);
}
}
The problem is that the function goes into the else statement of sendMessage which means mNode is null. mNode is a variable of type Node.
To get the node, I have this function
private void resolveNode() {
Wearable.NodeApi.getConnectedNodes(googleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
@Override
public void onResult(NodeApi.GetConnectedNodesResult nodes) {
for (Node node : nodes.getNodes()) {
mNode = node;
}
}
});
}
I've connected my phone with the Android Wear Virtual Device in Android Studio.
What am I doing wrong here?
When you call googleApiClient.connect(), the connection takes a short amount of time and this call does not block. So you need to wait until the connection succeeds with a call to onConnected() before you do any further calls.
Next, when you call resolveNode(), the mNode variable is not set instantly. The setResultCallback is executed a short time later, and so you should not call sendMessage() until the result is processed.
So you need to ensure proper ordering for everything here.
(Edit)
After going through the comments, it turns out the problem was caused by the connection to Google Play Services failing. This was because the emulator used was an old API 20 device, which has an old version of Google Play Services. Using the latest API 22 emulator will resolve the issue.
try with this to get Node