Kapouter
Kapouter

Reputation: 147

Listen to disconnected nodes

In a watch face configuration activity, i want to warn the user if its watch gets disconnected while he makes changes to the watch face configuration.

Wearable.NodeApi.addListener being deprecated, how can I listen to disconnected nodes in an activity ?

Using a WearableListenerService doesn't fit since I don't want to listen when the activity isn't open.

Upvotes: 0

Views: 763

Answers (1)

codingjeremy
codingjeremy

Reputation: 5741

The CapabilityApi should work. There are two ways to get a list of connected nodes based on capability including a callback for changes:

  1. Callback for Node changes: CapabilityApi.CapabilityListener
  2. Requesting current Nodes: Wearable.CapabilityApi.getCapability()

More details:

Below is a snippet from Google's RuntimePermissionsWear sample's MainWearActivity.java file. In the onConnected() method, it sets up a listener for changes in the nodes and requests a list of current nodes (covers both scenarios).

Please note, this sample uses a custom capability (both for phone and wear), so you might change that part. If you are using a custom capability, it must be declared in the wear.xml file. (Here is the one from the phone for the sample in case you are curious.)

    // Set up listeners for capability and message changes.
    Wearable.CapabilityApi.addCapabilityListener(
            mGoogleApiClient,
            this,
            Constants.CAPABILITY_PHONE_APP); // custom capability
    ...

    // Initial check of capabilities to find the phone.
    PendingResult<CapabilityApi.GetCapabilityResult> pendingResult =
            Wearable.CapabilityApi.getCapability(
                    mGoogleApiClient,
                    Constants.CAPABILITY_PHONE_APP, // custom capability
                    CapabilityApi.FILTER_REACHABLE);

    pendingResult.setResultCallback(new ResultCallback<CapabilityApi.GetCapabilityResult>() {
        @Override
        public void onResult(CapabilityApi.GetCapabilityResult getCapabilityResult) {

            if (getCapabilityResult.getStatus().isSuccess()) {
                CapabilityInfo capabilityInfo = getCapabilityResult.getCapability();
                // Realistically, there is only on phone node with this capability, but you should check for multiple nodes to be safe (if wearable, many more possibilities)
                mPhoneNodeId = pickBestNodeId(capabilityInfo.getNodes());

            } else {
                Log.d(TAG, "Failed CapabilityApi result: "
                        + getCapabilityResult.getStatus());
            }
        }
    });

Upvotes: 1

Related Questions