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() {
  AdvertisingOptions advertisingOptions =
      new AdvertisingOptions.Builder().setStrategy(STRATEGY).build();
  Nearby.getConnectionsClient(context)
      .startAdvertising(
          getUserNickname(), SERVICE_ID, connectionLifecycleCallback, advertisingOptions)
      .addOnSuccessListener(
          (Void unused) -> {
            // We're advertising!
          })
      .addOnFailureListener(
          (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 void startDiscovery() {
  DiscoveryOptions discoveryOptions =
      new DiscoveryOptions.Builder().setStrategy(STRATEGY).build();
  Nearby.getConnectionsClient(context)
      .startDiscovery(SERVICE_ID, endpointDiscoveryCallback, discoveryOptions)
      .addOnSuccessListener(
          (Void unused) -> {
            // We're discovering!
          })
      .addOnFailureListener(
          (Exception e) -> {
            // We're unable to start discovering.
          });
}

The EndpointDiscoveryCallback parameter is the callback that will be invoked when nearby advertisers are discovered or lost. See Manage Connections for details about defining this callback.

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