Hi and welcome to another tutorial from CodingDemos :)
In this tutorial, you will learn how to enable or disable the WIFI connection programmatically inside the emulator or physical device.
You will learn how to use the Android WIFI Manager API to be able to control the WIFI connection.
Note: Android WifiManager's setWifiEnabled API is deprecated in API 29, but you can still use it in older APIs.
Here are the steps:
1- Open up Android Studio.
2- Declare and initialize Android WifiManager like this: wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
3- Next, you need to check the current status of the WIFI connection using wifiManager.isWifiEnabled() and change the label of the Android Button based on the status. If the WIFI is ON, the button label will show "Turn WIFI OFF", and if the WIFI is OFF, the button label will show "Turn WIFI ON".
3- Inside the button Onclicklistener you also need to check the current WIFI status to turn the WIFI ON or OFF as well as to change the label of the button like this:
if (wifiManager.isWifiEnabled()) {
buttonWifi.setText("Turn WIFI ON");
wifiManager.setWifiEnabled(false);
} else if (!wifiManager.isWifiEnabled()) {
buttonWifi.setText("Turn WIFI OFF");
wifiManager.setWifiEnabled(true);
}
}
4- Finally, you need to add 2 permissions inside the Androidmanifest.xml file. These permissions will allow you to control the WIFI connection of the device. These are the permissions:
android:name="android.permission.ACCESS_WIFI_STATE"
android:name="android.permission.CHANGE_WIFI_STATE"
5- Now run and build the app to see the result :)
Links:
Android WifiManager's setWifiEnabled API: https://developer.android.com/referen...)
https://issuetracker.google.com/issue...
Website: https://www.codingdemos.com
FaceBook: / codingdemos