0

I want to connect to a specific wifi in android programmatically using kotlin.

Till sdk level 28 we were using WifiManager api to connect to a specific wifi network programmatically, this is working fine for me.

But from sdk level 29 this way is deprecated and new way of wifi connection is introduced which is Wi-Fi suggestion API to connect to a wifi with internet.

But I am not able to figure out how to connect to specific wifi network using this new Wi-Fi suggestion API

So please help me with it.

This it the code which I am using to connect to a specific wifi.

private fun connect(ssid: String, password:String): Int {
        if (android.os.Build.VERSION.SDK_INT >= 29) {

            val suggestion1: WifiNetworkSuggestion = WifiNetworkSuggestion.Builder()
                .setSsid(ssid)
                .setWpa2Passphrase(password)
                .build()
            val suggestionsList: MutableList<WifiNetworkSuggestion> = ArrayList()
            suggestionsList.add(suggestion1)

            val wifiManager =
                applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val status = wifiManager.addNetworkSuggestions(suggestionsList)
            if (status == 0) {
                Toast.makeText(this, "PSK network added", Toast.LENGTH_LONG).show()
//                Log.i(TAG, "PSK network added: $status")
            } else {
                Toast.makeText(this, "PSK network not added", Toast.LENGTH_LONG).show()
//                Log.i(TAG, "PSK network not added: $status")
            }

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

            val request = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
                .setNetworkSpecifier(specifier)
                .build()

            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

            val networkCallback = object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    // do success processing here..
                    println("on available");
                }

                override fun onUnavailable() {
                    // do failure processing here..
                    println("on unavailable");
                }
            }
            connectivityManager.requestNetwork(request, networkCallback)

            return 123
        } else {
            val networkSSID = ssid
            val networkPass = password

            val conf = WifiConfiguration()
            conf.SSID = "\"" + networkSSID + "\""

            conf.wepKeys[0] = "\"" + networkPass + "\"";
            conf.wepTxKeyIndex = 0;
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            conf.preSharedKey = "\""+ networkPass +"\"";
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            wifiManager.addNetwork(conf)
            var list = listOf<WifiConfiguration>()
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
            }
            else {
                list = wifiManager.configuredNetworks
            }
            for (i in list) {
                if (i.SSID != null && i.SSID == "\"" + networkSSID + "\"") {
                    wifiManager.disconnect()
                    wifiManager.enableNetwork(i.networkId, true)
                    wifiManager.reconnect()
                    break
                }
            }
            return ssid.length
        }
    }
1

1 Answer 1

0

for connect wifi

 override fun connectWiFi(ssid: String, password: String) {
        beforeEnableWifiSelectedWifiName = selectedWifi.SSID
        beforeEnableWifiSelectedWifiPassword = password
        if (checkWifiStatus()) {
            when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                    val wifiNetworkSpecifier: WifiNetworkSpecifier = if (password != "") {
                        WifiNetworkSpecifier.Builder()
                            .setSsid(beforeEnableWifiSelectedWifiName)
                            .setWpa2Passphrase(password)
                            .build()
                    } else {
                        WifiNetworkSpecifier.Builder()
                            .setSsid(beforeEnableWifiSelectedWifiName)
                            .build()
                    }


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

                    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

                    val networkCallback = object : ConnectivityManager.NetworkCallback() {
                        override fun onAvailable(network: Network) {
                            isHomeClick = false
                            super.onAvailable(network)
                            connectivityManager?.bindProcessToNetwork(network)
                        }


                        override fun onUnavailable() {
                            isHomeClick = false
                            super.onUnavailable()
                            showToast(getString(R.string.network_unavailable),true)
                        }

                        override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
                            isHomeClick = false
                            savePasswordAndWifiNameInDatabase(ssid,
                                selectedWifi.BSSID,
                                password,
                                getSecurityType(selectedWifi))
                            showToast(getString(R.string.connected),true)
                            super.onCapabilitiesChanged(network, networkCapabilities)
                        }


                    }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        showDialogForOpenWifiSetting(this) {
                            connectivityManager?.requestNetwork(networkRequest, networkCallback)
                        }
                    } else {
                        connectivityManager?.requestNetwork(networkRequest, networkCallback)
                    }
                }
                else -> {
                    val wifiConfig = WifiConfiguration().apply {
                        SSID = String.format("\"%s\"", beforeEnableWifiSelectedWifiName)
                        preSharedKey = String.format("\"%s\"", password)

                    }
                    with(wifiManager) {
                        val netId = addNetwork(wifiConfig)
                        disconnect()
                        enableNetwork(netId, true)
                        reconnect()
                    }
                }
            }
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Hey savan, I tried your solution but with you solution wifi is disconnecting and connecting to the same wifi network again.
is it not woking in your case
no it is not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.