如何通过Google Nearby Connections API检测并连接范围内全部活跃设备?
Hey there! Let's tackle your Nearby Connections API issues step by step. It's common to run into device discovery and multi-connection hiccups when getting started, so let's break down the fixes and best practices.
First, let's figure out why the new device can't see both active devices. Here are the most likely culprits:
1. Incorrect Strategy Selection
The Strategy you use dictates how many devices can discover and connect with each other:
Strategy.P2P_POINT_TO_POINTis strictly one-to-one—if you’re using this, you’ll only ever detect/connect to one device at a time.Strategy.P2P_STARis what you need for multi-device scenarios: it supports one host connecting to multiple clients, and all devices can discover each other if configured correctly.
2. Missing or Misconfigured Permissions
Nearby Connections relies on several permissions, especially on Android 12+. Double-check your AndroidManifest.xml and runtime permissions:
<!-- Base permissions --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- Bluetooth permissions (Android 12+) --> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" /> <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <!-- Legacy Bluetooth permissions (pre-Android 12) --> <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
Make sure you’re requesting these permissions at runtime (location and Bluetooth permissions require explicit user consent).
3. Mismatched SERVICE_ID
All devices must use the exact same SERVICE_ID to discover each other. If one device uses "com.yourapp.nearby" and another uses "com.yourapp.nearby.dev", they won’t see each other. Double-check that this string is identical across all instances of your app.
4. Limited Scan Duration or Background Restrictions
Nearby’s scan isn’t continuous by default. If your scan times out before detecting the second device, you’ll miss it. Also, Android 12+ restricts background scanning—make sure your app is in the foreground when scanning, or request ACCESS_BACKGROUND_LOCATION if you need background discovery (note: this is a sensitive permission users may hesitate to grant).
Once you’ve fixed the discovery issues, here’s how to set up multi-device connections:
1. Switch to P2P_STAR Strategy
Update your advertising and discovery code to use Strategy.P2P_STAR:
// Initialize client NearbyConnectionsClient client = Nearby.getConnectionsClient(context); // Advertising options with P2P_STAR AdvertisingOptions advertisingOpts = new AdvertisingOptions.Builder() .setStrategy(Strategy.P2P_STAR) .build(); // Discovery options with P2P_STAR DiscoveryOptions discoveryOpts = new DiscoveryOptions.Builder() .setStrategy(Strategy.P2P_STAR) .build();
2. Handle Discovery and Connection Callbacks
Set up callbacks to detect devices and manage connections. Maintain a list of connected endpoints to keep track of all active devices:
// Track connected endpoints List<String> connectedEndpoints = new ArrayList<>(); // Discovery callback to handle found devices DiscoveryCallback discoveryCallback = new DiscoveryCallback() { @Override public void onEndpointFound(String endpointId, DiscoveredEndpointInfo info) { // Send connection request to the found device client.requestConnection( "MyDeviceName", // Your device's display name endpointId, connectionCallback ).addOnFailureListener(e -> { // Handle request failure }); } @Override public void onEndpointLost(String endpointId) { // Remove lost device from your list if needed connectedEndpoints.remove(endpointId); } }; // Connection callback to handle connection states ConnectionCallback connectionCallback = new ConnectionCallback() { @Override public void onConnectionInitiated(String endpointId, ConnectionInfo connectionInfo) { // Accept the connection request (you can add a user confirmation step here too) client.acceptConnection(endpointId, payloadCallback) .addOnFailureListener(e -> { // Handle acceptance failure }); } @Override public void onConnectionResult(String endpointId, ConnectionResolution result) { switch (result.getStatus().getStatusCode()) { case ConnectionsStatusCodes.STATUS_OK: // Connection successful—add to your list connectedEndpoints.add(endpointId); break; case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED: // Connection was rejected break; case ConnectionsStatusCodes.STATUS_ERROR: // Connection failed due to an error break; } } @Override public void onDisconnected(String endpointId) { // Remove disconnected device from your list connectedEndpoints.remove(endpointId); } }; // Payload callback to handle incoming messages PayloadCallback payloadCallback = new PayloadCallback() { @Override public void onPayloadReceived(String endpointId, Payload payload) { // Process incoming message byte[] data = PayloadBytes.asBytes(payload); String message = new String(data); } @Override public void onPayloadTransferUpdate(String endpointId, PayloadTransferUpdate update) { // Handle transfer progress (optional) } };
3. Start Advertising and Scanning
For full mutual discovery, have all devices advertise and scan:
// Start advertising your device client.startAdvertising( "MyDeviceName", "com.yourapp.nearby", // Your shared SERVICE_ID advertisingCallback, advertisingOpts ); // Start scanning for other devices client.startDiscovery( "com.yourapp.nearby", discoveryCallback, discoveryOpts );
4. Send Messages to All Connected Devices
Use your connectedEndpoints list to broadcast messages to all devices:
// Create a payload (text example) Payload payload = Payload.fromBytes("Hello all connected devices!".getBytes()); // Send to every connected endpoint for (String endpoint : connectedEndpoints) { client.sendPayload(endpoint, payload); }
- Ensure Bluetooth and Wi-Fi are enabled on all devices (Nearby Connections uses both for optimal discovery).
- Test on physical devices—emulators often have limited support for Nearby Connections.
- Avoid rapid restarting of advertising/scanning; give the API a few seconds to detect devices.
内容的提问来源于stack exchange,提问作者Karthik

