Search code examples
androidkotlinwifiwifimanager

How to connect to Wifi network programatically on Android 10 and above?


val ssid = "Your WiFi SSID"
val password = "Your WiFi password"
val networkSSID = "\"$ssid\""
val networkPassword = "\"$password\""
val wifiConfiguration = WifiConfiguration()
wifiConfiguration.SSID = networkSSID
wifiConfiguration.preSharedKey = networkPassword
val networkId = wifiManager.addNetwork(wifiConfiguration)
wifiManager.disconnect()
wifiManager.enableNetwork(networkId, true)
wifiManager.reconnect()

Used this code but it is not working on Android 10 and above.Also followed https://github.com/ThanosFisherman/WifiUtils but which also not working on Android 10 and above. Can some one suggest how to connect to wifi network.


Solution

  • You should try ConnectivityManager and NetworkCallbacks to do this task like this way:

    @RequiresApi(Build.VERSION_CODES.Q)
    fun connectToWiFi(pin: String, ssid:String) {
        val connectivityManager =
             context.getSystemService(Context.CONNECTIVITY_SERVICE) as 
             ConnectivityManager
        val specifier = WifiNetworkSpecifier.Builder()
            .setSsid(ssid)
            .setWpa2Passphrase(pin)
            .setSsidPattern(PatternMatcher(ssid, PatternMatcher.PATTERN_PREFIX))
            .build()
        val request = NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .setNetworkSpecifier(specifier)
            .build()
        val networkCallback = object : NetworkCallback() {
            override fun onAvailable(network: Network) {
                super.onAvailable(network)
              showToast(context,context.getString(R.string.connection_success))
            }
    
            override fun onUnavailable() {
                super.onUnavailable()
                showToast(context,context.getString(R.string.connection_fail))
            }
    
            override fun onLost(network: Network) {
                super.onLost(network)
                showToast(context,context.getString(R.string.out_of_range))
            }
        }
      connectivityManager.requestNetwork(request, networkCallback)
    }