privatefinalConnectionLifecycleCallbackconnectionLifecycleCallback=newConnectionLifecycleCallback(){@OverridepublicvoidonConnectionInitiated(StringendpointId,ConnectionInfoconnectionInfo){//Automaticallyaccepttheconnectiononbothsides.Nearby.getConnectionsClient(context).acceptConnection(endpointId,payloadCallback);}@OverridepublicvoidonConnectionResult(StringendpointId,ConnectionResolutionresult){switch(result.getStatus().getStatusCode()){caseConnectionsStatusCodes.STATUS_OK->{//We're connected! Can now start sending and receiving data.}caseConnectionsStatusCodes.STATUS_CONNECTION_REJECTED->{//Theconnectionwasrejectedbyoneorbothsides.}caseConnectionsStatusCodes.STATUS_ERROR->{//Theconnectionbrokebeforeitwasabletobeaccepted.}default->{//Unknownstatuscode}}}@OverridepublicvoidonDisconnected(StringendpointId){//We've been disconnected from this endpoint. No more data can be//sentorreceived.}};
@OverridepublicvoidonConnectionInitiated(StringendpointId,ConnectionInfoinfo){newAlertDialog.Builder(context).setTitle("Accept connection to "+info.getEndpointName()).setMessage("Confirm the code matches on both devices: "+info.getAuthenticationDigits()).setPositiveButton("Accept",(DialogInterfacedialog,intwhich)->
//Theuserconfirmed,sowecanaccepttheconnection.Nearby.getConnectionsClient(context).acceptConnection(endpointId,payloadCallback)).setNegativeButton(android.R.string.cancel,(DialogInterfacedialog,intwhich)->
//Theusercanceled,soweshouldrejecttheconnection.Nearby.getConnectionsClient(context).rejectConnection(endpointId)).setIcon(android.R.drawable.ic_dialog_alert).show();}
[null,null,["最后更新时间 (UTC):2025-08-13。"],[[["\u003cp\u003eNearby Connections allows devices to discover and connect to each other when in close proximity.\u003c/p\u003e\n"],["\u003cp\u003eBoth the discoverer and advertiser must accept the connection before data transfer can occur.\u003c/p\u003e\n"],["\u003cp\u003eConnections can be authenticated using a token to enhance security and ensure connection to the intended device.\u003c/p\u003e\n"],["\u003cp\u003eIt is crucial to implement authentication to protect against security vulnerabilities.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eConnectionLifecycleCallback\u003c/code\u003e handles connection events like initiation, acceptance/rejection, and disconnection.\u003c/p\u003e\n"]]],[],null,["# Manage connections\n\nInitiate a connection\n---------------------\n\nWhen nearby devices are found, the discoverer can initiate connections. The\nfollowing example requests a connection with a device as soon as it is discovered. \n\n```transact-sql\nprivate final EndpointDiscoveryCallback endpointDiscoveryCallback =\n new EndpointDiscoveryCallback() {\n @Override\n public void onEndpointFound(String endpointId, DiscoveredEndpointInfo info) {\n // An endpoint was found. We request a connection to it.\n Nearby.getConnectionsClient(context)\n .requestConnection(getLocalUserName(), endpointId, connectionLifecycleCallback)\n .addOnSuccessListener(\n (Void unused) -\u003e {\n // We successfully requested a connection. Now both sides\n // must accept before the connection is established.\n })\n .addOnFailureListener(\n (Exception e) -\u003e {\n // Nearby Connections failed to request the connection.\n });\n }\n\n @Override\n public void onEndpointLost(String endpointId) {\n // A previously discovered endpoint has gone away.\n }\n };\n```\n\nDepending on your use case, you may wish to instead display a list of discovered\ndevices to the user, allowing them to choose which devices to connect to.\n\nAccept or reject a connection\n-----------------------------\n\nAfter the discoverer has requested a connection to an advertiser, both sides are\nnotified of the connection initiation process via the `onConnectionInitiated()`\nmethod of the\n[`ConnectionLifecycleCallback`](/android/reference/com/google/android/gms/nearby/connection/ConnectionLifecycleCallback)\ncallback. Note that this callback is passed in to `startAdvertising()` on the\nadvertiser and `requestConnection()` on the discoverer, but from this point\nforward, the API is symmetric.\n\nNow both sides must choose whether to accept or reject the connection via a call\nto `acceptConnection()` or `rejectConnection()`, respectively. The connection is\nfully established only when both sides have accepted. If one or both reject, the\nconnection is discarded. Either way, the result is delivered to\n`onConnectionResult()`.\n\nThe following code snippet shows how to implement this callback: \n\n```gdscript\nprivate final ConnectionLifecycleCallback connectionLifecycleCallback =\n new ConnectionLifecycleCallback() {\n @Override\n public void onConnectionInitiated(String endpointId, ConnectionInfo connectionInfo) {\n // Automatically accept the connection on both sides.\n Nearby.getConnectionsClient(context).acceptConnection(endpointId, payloadCallback);\n }\n\n @Override\n public void onConnectionResult(String endpointId, ConnectionResolution result) {\n switch (result.getStatus().getStatusCode()) {\n case ConnectionsStatusCodes.STATUS_OK -\u003e {\n // We're connected! Can now start sending and receiving data.\n }\n case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED -\u003e {\n // The connection was rejected by one or both sides.\n }\n case ConnectionsStatusCodes.STATUS_ERROR -\u003e {\n // The connection broke before it was able to be accepted.\n }\n default -\u003e {\n // Unknown status code\n }\n }\n }\n\n @Override\n public void onDisconnected(String endpointId) {\n // We've been disconnected from this endpoint. No more data can be\n // sent or received.\n }\n };\n```\n\nAgain, this example shows the connection being automatically accepted by both sides, but depending on your use case you may wish to present this choice to the user in some way.\n\n### Authenticate a connection\n\nWhen a connection is requested, your app can *authenticate* the connection by\nusing the authentication token provided to `onConnectionInitiated()`. This\nprovides a way to let users confirm that they are connecting to the intended\ndevice. Both devices are given the same token, which is a short random string;\nit's up to you to decide how to verify it. Typically this involves showing the\ntoken on both devices and asking the users to manually compare and confirm,\nsimilar to a bluetooth pairing dialog.\n| **Caution:** While authentication is optional, connections established without authentication are insecure, and can expose devices to severe security vulnerabilities. To avoid this, always use authentication to secure your connections.\n\nThis sample code demonstrates one way to authenticate by displaying the\nauthentication token to the user in an `AlertDialog`: \n\n```gdscript\n@Override\npublic void onConnectionInitiated(String endpointId, ConnectionInfo info) {\n new AlertDialog.Builder(context)\n .setTitle(\"Accept connection to \" + info.getEndpointName())\n .setMessage(\"Confirm the code matches on both devices: \" + info.getAuthenticationDigits())\n .setPositiveButton(\n \"Accept\",\n (DialogInterface dialog, int which) -\u003e\n // The user confirmed, so we can accept the connection.\n Nearby.getConnectionsClient(context)\n .acceptConnection(endpointId, payloadCallback))\n .setNegativeButton(\n android.R.string.cancel,\n (DialogInterface dialog, int which) -\u003e\n // The user canceled, so we should reject the connection.\n Nearby.getConnectionsClient(context).rejectConnection(endpointId))\n .setIcon(android.R.drawable.ic_dialog_alert)\n .show();\n}\n```"]]