API Wi-Fi Network Request per la connettività peer-to-peer
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Sui dispositivi Android 10 (livello API 29) e versioni successive, puoi utilizzare una nuova API peer-to-peer per
avviare la configurazione di dispositivi secondari come Chromecast e hardware
Google Home. Questa funzionalità consente all'app di chiedere all'utente di cambiare il punto di accesso a cui è connesso il dispositivo utilizzando
WifiNetworkSpecifier
per descrivere le proprietà di una rete richiesta.
Imposta un filtro di rete per trovare le reti a cui connettersi, insieme alle credenziali richieste.
Decidi una combinazione di SSID,
SSID pattern,
BSSID,
e BSSID pattern
per impostare il filtro di rete in ogni richiesta, in base ai seguenti
requisiti:
Ogni richiesta deve fornire almeno uno dei seguenti valori: SSID, SSID pattern,
BSSID o BSSID pattern
Ogni richiesta può impostare solo uno dei valori SSID o SSID pattern
Ogni richiesta può impostare solo uno dei valori BSSID o BSSID pattern
Aggiungi gli identificatori alla richiesta di rete insieme a un'istanza
NetworkCallback
per monitorare lo stato della richiesta.
Se l'utente accetta la richiesta e la connessione alla rete va a buon fine, viene richiamato NetworkCallback.onAvailable() sull'oggetto callback. Se l'utente rifiuta la richiesta o se la
connessione alla rete non va a buon fine,
NetworkCallback.onUnavailable()
viene richiamato sull'oggetto callback.
L'avvio della richiesta di connessione a un dispositivo peer apre una finestra di dialogo sullo
stesso dispositivo, da cui l'utente del dispositivo può accettare la richiesta di connessione.
Ignorare l'approvazione dell'utente
Una volta che l'utente approva la connessione a una rete in risposta a una richiesta di un'app specifica, il dispositivo memorizza l'approvazione per il punto di accesso specifico.
Se l'app fa una richiesta specifica per
connettersi di nuovo a quel punto di accesso, il dispositivo salta la fase di approvazione dell'utente
e si connette automaticamente alla rete. Se l'utente sceglie di dimenticare la rete mentre è connesso a una rete richiesta dall'API, l'approvazione memorizzata per quella combinazione di app e rete viene rimossa e qualsiasi richiesta futura dall'app deve essere approvata nuovamente dall'utente. Se l'app
effettua una richiesta non specifica, ad esempio con un pattern SSID o BSSID, l'utente
deve approvare la richiesta.
Esempio di codice
Il seguente esempio di codice mostra come connettersi a una rete aperta con un prefisso SSID
di "test" e un OUI BSSID di "10:03:23":
Kotlin
valspecifier=WifiNetworkSpecifier.Builder().setSsidPattern(PatternMatcher("test",PatternMatcher.PATTERN_PREFIX)).setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),MacAddress.fromString("ff:ff:ff:00:00:00")).build()valrequest=NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(specifier).build()valconnectivityManager=context.getSystemService(Context.CONNECTIVITY_SERVICE)asConnectivityManagervalnetworkCallback=object:ConnectivityManager.NetworkCallback(){...overridefunonAvailable(network:Network?){// do success processing here..}overridefunonUnavailable(){// do failure processing here..}...}connectivityManager.requestNetwork(request,networkCallback)...// Release the request when done.connectivityManager.unregisterNetworkCallback(networkCallback)
Java
finalNetworkSpecifierspecifier=newWifiNetworkSpecifier.Builder().setSsidPattern(newPatternMatcher("test",PatternMatcher.PATTERN_PREFIX)).setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),MacAddress.fromString("ff:ff:ff:00:00:00")).build();finalNetworkRequestrequest=newNetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).setNetworkSpecifier(specifier).build();finalConnectivityManagerconnectivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);finalNetworkCallbacknetworkCallback=newNetworkCallback(){...@OverridevoidonAvailable(...){// do success processing here..}@OverridevoidonUnavailable(...){// do failure processing here..}...};connectivityManager.requestNetwork(request,networkCallback);...// Release the request when done.connectivityManager.unregisterNetworkCallback(networkCallback);
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-08-27 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-08-27 UTC."],[],[],null,["On Android 10 (API level 29) and higher devices, you can use a new peer to peer API to\nbootstrap configuration for secondary devices like Chromecast and Google Home\nhardware. This feature enables your app to prompt the user to change the access\npoint that the device is connected to by using\n[`WifiNetworkSpecifier`](/reference/android/net/wifi/WifiNetworkSpecifier)\nto describe properties of a requested network.\n\nTo use this API, do the following:\n\n1. Create a Wi-Fi network specifier using\n [`WifiNetworkSpecifier.Builder`](/reference/android/net/wifi/WifiNetworkSpecifier.Builder).\n\n2. Set a network filter to match networks to connect to, along with required\n credentials.\n\n3. Decide on a combination of [`SSID`](/reference/android/net/wifi/WifiNetworkSpecifier.Builder#setssid),\n [`SSID pattern`](/reference/android/net/wifi/WifiNetworkSpecifier.Builder#setssidpattern),\n [`BSSID`](/reference/android/net/wifi/WifiNetworkSpecifier.Builder#setbssid),\n and [`BSSID pattern`](/reference/android/net/wifi/WifiNetworkSpecifier.Builder#setbssidpattern)\n to set the network filter in each request, subject to the following\n requirements:\n\n - Each request should provide at least one of `SSID`, `SSID pattern`, `BSSID`, or `BSSID pattern`\n - Each request can set only one of `SSID` or `SSID pattern`\n - Each request can set only one of `BSSID` or `BSSID pattern`\n4. Add the specifiers to the network request along with a\n [`NetworkCallback`](/reference/android/net/ConnectivityManager.NetworkCallback)\n instance to track the status of the request.\n\n If the user accepts the request and the connection to the network is\n successful,\n [`NetworkCallback.onAvailable()`](/reference/android/net/ConnectivityManager.NetworkCallback#onAvailable(android.net.Network))\n is invoked on the callback object. If the user denies the request or if the\n connection to the network is unsuccessful,\n [`NetworkCallback.onUnavailable()`](/reference/android/net/ConnectivityManager.NetworkCallback#onUnavailable())\n is invoked on the callback object.\n\nInitiating the request to connect to a peer device launches a dialog box on the\nsame device, from which that device's user can accept the connection request.\n| **Note:** Creating a connection using this API does not provide an internet connection to the app or to the device. To provide an internet connection to the apps on a device, use the [Wi-Fi Suggestion API](/develop/connectivity/wifi/wifi-suggest) instead.\n\nBypassing user approval\n\nOnce the user approves a network to connect to in response to a request from a\nspecific app, the device stores the approval for the particular access point.\nIf the app makes a specific request to\nconnect to that access point again, the device skips the user approval phase\nand automatically connects to the network. If the user chooses to forget the\nnetwork while connected to a network requested by the API, then this stored\napproval for that combination of app and network is removed, and any future\nrequest from the app must be approved by the user again. If the app\nmakes a non-specific request, such as with an SSID or BSSID pattern, then the\nuser must approve the request.\n\nCode sample\n\nThe following code sample shows how to connect to an open network with an SSID\nprefix of `\"test\"` and a BSSID OUI of `\"10:03:23\"`: \n\nKotlin \n\n```kotlin\nval specifier = WifiNetworkSpecifier.Builder()\n .setSsidPattern(PatternMatcher(\"test\", PatternMatcher.PATTERN_PREFIX))\n .setBssidPattern(MacAddress.fromString(\"10:03:23:00:00:00\"), MacAddress.fromString(\"ff:ff:ff:00:00:00\"))\n .build()\n\nval request = NetworkRequest.Builder()\n .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)\n .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)\n .setNetworkSpecifier(specifier)\n .build()\n\nval connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager\n\nval networkCallback = object : ConnectivityManager.NetworkCallback() {\n ...\n override fun onAvailable(network: Network?) {\n // do success processing here..\n }\n\n override fun onUnavailable() {\n // do failure processing here..\n }\n ...\n}\nconnectivityManager.requestNetwork(request, networkCallback)\n...\n// Release the request when done.\nconnectivityManager.unregisterNetworkCallback(networkCallback)\n```\n\nJava \n\n```java\nfinal NetworkSpecifier specifier =\n new WifiNetworkSpecifier.Builder()\n .setSsidPattern(new PatternMatcher(\"test\", PatternMatcher.PATTERN_PREFIX))\n .setBssidPattern(MacAddress.fromString(\"10:03:23:00:00:00\"), MacAddress.fromString(\"ff:ff:ff:00:00:00\"))\n .build();\n\nfinal NetworkRequest request =\n new NetworkRequest.Builder()\n .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)\n .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)\n .setNetworkSpecifier(specifier)\n .build();\n\nfinal ConnectivityManager connectivityManager = (ConnectivityManager)\n context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\nfinal NetworkCallback networkCallback = new NetworkCallback() {\n ...\n @Override\n void onAvailable(...) {\n // do success processing here..\n }\n\n @Override\n void onUnavailable(...) {\n // do failure processing here..\n }\n ...\n};\nconnectivityManager.requestNetwork(request, networkCallback);\n...\n// Release the request when done.\nconnectivityManager.unregisterNetworkCallback(networkCallback);\n```"]]