Android Q, able to connect Wifi pragmatically but not able to access Internet-ThrowExceptions

Exception or error:

In Android Q, I can scan, select and connect to wifi via programmatically. But I am not able to get the internet via the wifi I connected even tho it has internet access.

Below is my code:

 val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
            .setSsid("Wifi-SSID")
            .setWpa2Passphrase("WiFi-password")
            .build()


val networkRequest = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .setNetworkSpecifier(wifiNetworkSpecifier)
            .build()

var connectivityManager =
            applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

var connectivity = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                Log.d("TAG: ", "Connected")
                connectivityManager.bindProcessToNetwork(network)
                super.onAvailable(network)
            }

            override fun onUnavailable() {
                super.onUnavailable()
                Log.d("TAG: ", "Not able to connect")
            }

            override fun onLost(network: Network) {
                Log.d("TAG: ", "Connection lost")
            }
        }
connectivityManager?.requestNetwork(networkRequest, connectivity)

TIA

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *