Advertise and Discover

Once the user has granted all required permissions, your app can begin to advertise and discover in order to find nearby devices.

First, choose a Strategy for your use case. The Strategy you select determines the connection topology for your app (one advertiser to N discoverers, or M advertisers to N discoverers).

On devices that will advertise, call startAdvertising() with the desired Strategy and a serviceId parameter that identifies your app.

On devices that will discover nearby advertisers, call startDiscovery() with the same Strategy and serviceId.

The serviceId value must uniquely identify your app. As a best practice, use the package name of your app (for example, com.google.example.myapp).

The following example shows how to advertise:

private void startAdvertising() {
  Nearby.getConnections(context).startAdvertising(
          getUserNickname(),
          SERVICE_ID,
          mConnectionLifecycleCallback,
          new AdvertisingOptions(STRATEGY))
      .addOnSuccessListener(
        new OnSuccessListener<Void>() {
          @Override
          public void onSuccess(Void unusedResult) {
            // We're advertising!
          }
        })
      .addOnFailureListener(
        new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // We were unable to start advertising.
          }
        });
  }

The ConnectionLifecycleCallback parameter is the callback that will be invoked when discoverers request to connect to the advertiser. See Manage Connections for details about defining this callback.

The following example shows how to discover:

private final EndpointDiscoveryCallback mEndpointDiscoveryCallback =
  new EndpointDiscoveryCallback() {
    @Override
    public void onEndpointFound(
        String endpointId, DiscoveredEndpointInfo discoveredEndpointInfo) {
      // An endpoint was found!
    }

    @Override
    public void onEndpointLost(String endpointId) {
      // A previously discovered endpoint has gone away.
    }
  };

private void startDiscovery() {
  Nearby.getConnections(context).startDiscovery(
          SERVICE_ID,
          mEndpointDiscoveryCallback,
          new DiscoveryOptions(STRATEGY))
      .addOnSuccessListener(
        new OnSuccessListener<Void>() {
          @Override
          public void onSuccess(Void unusedResult) {
            // We're discovering!
          }
        })
      .addOnFailureListener(
        new OnFailureListener() {
          @Override
          public void onFailure(@NonNull Exception e) {
            // We were unable to start discovering.
          }
        });
}

Call stopAdvertising() when you no longer need to advertise, and stopDiscovery() when you no longer need to discover.