In Android development, you can programmatically configure the wireless connectivity of you android devices. Let’s find out how to do that, Android comes with a number of system services that are always on, and running and readily available for Android Developers. In Android Development, like all other systems services, provides an API for managing all aspects of the Wi-Fi Connectivity. WifiManager (package name: android.net.wifi) is the class which provides the primary API for the WIFI services. An operation for network connectivity can be done using the ConnectivityManager class (package name: android.net).
To get an instance of the System Service or rather a handle for the system service you need to call Context.getSystemService(“SERVICE_NAME”)
Manifest File Permissions
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE”/> <uses-permission android:name=”android.permission.CHANGE_WIFI_STATE”/>
Getting the WIFI System Service in Android development
WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
Enabling and disabling the WIFI in Android development
if (!mWifiManager.isWifiEnabled()) if (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLING) mWifiManager.setWifiEnabled(true);
Creating and managing Wi-Fi Connections in Android development
For creating configurations Android has provided a class named WifiConfiguration.
//Adding a OPEN network WifiConfiguration config= new WifiConfiguration(); config.SSID=”\”SSID_OF_NETOWRK\””; config.allowedKeyManagement.set(KeyMgmt.NONE); config.status=WifiConfiguration.Status.ENABLED; int netId=mWifiManager.addNetwork(config); mWifiManager.saveConfiguration(); mWifiManager.reconnect();
There is a trick in adding the SSID for the new WifiConfiguration. The SSID needs to be within quotes and if not specified that way the network will never get added to the configured list of networks.
On calling the addNetwork method the configuration is added to the list of configured networks and a network Id is returned which signifies the particular wifi configuration.
After adding the network several other things can be done like forcing the network to be used as the default connection. In that case if the device is connected to the current network it will be disconnected from that network and associated to the specified network.
The WifiManager class has several other methods like disconnect, reassociate, removeNetwork, updateNetwork, startScan.