jzplusplus
jzplusplus

Reputation: 76

What is the easiest way to detect if an Android Wear device is connected to the phone?

I want my app to behave differently if an Android Wear device is currently connected. What is the easiest way to detect this?

I believe that you could use this method which is in Google Play Services, but that seems like a lot of overhead just to see if the device is there or not. Is there any other way?

Upvotes: 5

Views: 3963

Answers (3)

Ken
Ken

Reputation: 1393

NodeAPI can check whether your Android Wear device and phone are connected or not in a simple way like this:

This is the callback function when you call:

private void checkNodeAPI(){
    Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(this, 1000, TimeUnit.MILLISECONDS);
}

//Callback

@Override
public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
    if (getConnectedNodesResult != null && getConnectedNodesResult.getNodes() != null){
        mWearableConnected = false;
        for (Node node : getConnectedNodesResult.getNodes()){
            if (node.isNearby()){
                mWearableConnected = true;
            }
        }
    }
    Log.v("TEST", "mWearableConnected: " + mWearableConnected);
}

getConnectedNodes() is an async function, so the result is just returned after a while, you can not get it immediately.

To receive the event when an Android Wear connects/disconnects to your phone, you can use this below function to add listener:

Wearable.NodeApi.addListener(mGoogleApiClient, this);

@Override
public void onPeerConnected(Node node) {
    Log.v("TEST", "onPeerConnected");
    mWearableConnected = true;
}

@Override
public void onPeerDisconnected(Node node) {
    Log.v("TEST", "onPeerDisconnected");
    checkNodeAPI();
}

But this listener is not always called on some Android Wear devices.

Upvotes: 3

Tony Wickham
Tony Wickham

Reputation: 4766

You could also have a boolean value (say mIsConnected) that is set to true in onPeerConnected and false in onPeerDisconnected.

If you are using a WearableListenerService, these methods will automatically be included and you just have to override them: onPeerConnected(Node peer) and onPeerDisconnected(Node peer). If you want to do this in an Activity or something instead, just implement NodeApi.NodeListener, which has those methods. Make sure to add it to your Google API client (addListener(mGoogleApiClient, this)).

Upvotes: 1

matiash
matiash

Reputation: 55380

You must use Wearable.NodesApi.getConnnectedNodes() API, as you state.

There is no other method to do this, at least currently.

Upvotes: 1

Related Questions