Android – Connecting to WiFi programmatically
|We might have some scenarios , where application needs to connect the device to a WiFi access point. Application might have got the details of the Access point from other means like Bluetooth or image processing of the router image. Google showcased this feature using Google lens , where you point you camera at a wifi router and your device connects to the router
In this blog we will see how we can do this using kotlin as our programming language, we have already seen how to setup environment for kotlin development here.
The programs assumes that it already got the access point details to which it needs to connect.
Program flow
We have a simple activity with a button ,The real actions happens when we click the button
First the program checks if the device is already connected to requested AP, if yes it will simply shows a toast message
Then it will try to get the WiFiConfig the given ssid, if the WiFiConfig is not already present, it will create a new WiFiConfig for the ssid. So if a WiFiConfig is already present for a given ssid, it will not recreate it..if the passphrase is changed it might fail to connect, in your scenarios if it likely for the passphrase to change , then it is better to create the config on every time.
Once we got the WiFiConfig , we will disconnect from the present network, enable our WiFiConfig, then reconnect
We also have BroadCast Receiver which will show a toast message when the device is connected to the AP
We need to request for permissions and register to receive board casts
We have reused the layout from the previous example
The Config object has the details of AP
object Config{ const val SSID="\"ssid\"" const val PASS="\"passphrase\"" }
project setup
Screen shot of the app
Nice tutorial thanks !!
If we have a disable wifi on our phone this example isn’t work… In this case we have that we are already connected to the network, although this is not true 🙂
That would solve the problem we can using:
fun isConected(ssid: String): Boolean {
val vm: WifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
/*Check enable wifi, if it is disable -> enable it*/
if(!vm.isWifiEnabled){
vm.isWifiEnabled = true
return false
}
if(vm.connectionInfo.ssid == ssid) {
return true
}
return false
}
thanks
Great and an informative article!