Search code examples
javaandroidkotlinwifissid

Connect to specific WiFi (Android Q)


In my app, I'm trying to connect automatically to a specific SSID (in android Q). I'm using "WifiNetworkSpecifier","NetworkRequest" and "ConnectivityManager" classes to do that. When I do a request, then a dialog appears on screen asking me to connect to this SSID, I click and then it connects. But there are two problems:

  1. It's not really connected (no internet), I have to disable and enable WiFi to have the chance to be really connected!

  2. When I clear app from memory it is automatically disconnected.

I'm looking to resolve these problems, but there is not enough example or sample. This is what I do in my source code:

fun connectToWifi(networkSSID: String, networkPassword: String?, bssid: String?)
        val specifier = WifiNetworkSpecifier.Builder()
            .setSsid(networkSSID)
        if (networkPassword != null) {
            specifier.setWpa2Passphrase(networkPassword)
        }
        if (bssid != null) {
            specifier.setBssid(MacAddress.fromString(bssid))
        }
        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(specifier.build())
            .build()
        val connectivityManager =
            singletonArgument.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network?) {
                Log.d(TAG, "network available")
            }

            override fun onUnavailable() {
                Log.d(TAG, "network unavailable")
            }
        }
        connectivityManager.requestNetwork(request, networkCallback)
}

Solution

  • As per this thread (https://support.google.com/pixelphone/thread/13670154?hl=en), this is a known issue on some of the devices which Google will be fixing soon. Just check if it works with 2.4GHz SSID. I hope it helps you.