Search code examples
androidwifi

Connecting to wifi with ConnectivityManager not possible


I'm trying to connect to a wifi with code. Here is my simplified code:

val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
    .setSsid(ssid)
    .setWpa2Passphrase(password)
    .build()

val networkRequest = NetworkRequest.Builder().apply {
    addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    if (useCapabilities) {
        addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
    }
    setNetworkSpecifier(wifiNetworkSpecifier)
}.build()

connectivityManager.requestNetwork(networkRequest, networkCallback)

The full code can be found here
When useCapabilities is true I get no visual feedback, the callbacks are not helpful too. When I set the capabilities onUnavailable() is called, but I see no reason why. I can connect with the same network which I try it by hand.

I have a full sample app here: https://github.com/rekire/WifiBug

Please tell me what I'm doing wrong. I'm using a Pixel 6 with Android 12.


Solution

  • WifiNetworkSpecifier is not meant to work with capability NET_CAPABILITY_INTERNET so it will always call onUnavailable. I explain in my self-answered question here: https://stackoverflow.com/a/73178258/467509

    I personally think Google should tell you this in Android Studio in a linter or something, and not just call onUnavailable and bury a debug message in LogCat.