AI-generated Key Takeaways
-
Your app can advertise and discover nearby devices to establish connections after necessary permissions are granted.
-
Choose a
Strategy
to define the connection topology (one-to-many or many-to-many) for your app's discovery and advertising. -
Use
startAdvertising()
andstartDiscovery()
with a uniqueserviceId
(preferably your app's package name) for advertising and discovering, respectively. -
Implement
ConnectionLifecycleCallback
andEndpointDiscoveryCallback
to manage connection requests and discovered devices. -
Call
stopAdvertising()
andstopDiscovery()
when advertising and discovering are no longer needed, respectively, but be aware of their impact on ongoing connections and future discoveries.
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( getLocalUserName(), 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.