Reputation: 2862
I am trying to connect to the wfi network which I have scanned. For testing I am giving ssid and key to wifi configurration and connecting to the network but in device its not getting connected.
Using following method to connect to the network.
fun connectToANewWifiNetwork() {
val wifiConfig = WifiConfiguration()
wifiConfig.SSID = String.format("\"%s\"", "GK")
wifiConfig.preSharedKey = String.format("\"%s\"", "Sid_GK_2417")
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val netId = wifiManager.addNetwork(wifiConfig)
wifiManager.enableNetwork(netId, true)
wifiManager.reconnect();
ProgressDialogUtils.getInstance().hideProgress()
}
Also is there any way to detect if we are connected to the given network?
What am I doing wrong here..?
Please help...
Upvotes: 0
Views: 849
Reputation: 134704
If you are running on Android 10 or higher, you'll need to switch to using the WifiNetworkSpecifier
mechanism, which requires user interaction in order to connect. For example:
val specifier =
WifiNetworkSpecifier.Builder()
.setSsid("GK")
.setWpa2Passphrase("Sid_GK_2417")
.build()
val networkRequest =
NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier)
.build()
val networkCallback = object : NetworkCallback() {
override fun onAvailable(network: Network) {
// Connected to network here
}
}
context.getSystemService(ConnectivityManager.class)
.requestNetwork(networkRequest, networkCallback)
https://developer.android.com/reference/android/net/wifi/WifiNetworkSpecifier.Builder?hl=en#build()
Upvotes: 1