Verify HTTP URL with PHP
November 28, 2012Website Security Measures
November 28, 2012First you need to have user permissions to access WiFi state and change it. To do so add following XML nodes in your app’s Manifest XML file under root node.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Next we need to declare a method toggleWIFI() which will be responsible for WiFi toggle. You can declare toggleWIFI() in your desired Activity class.
public boolean toggleWIFI(Context mContext) { // function body }
We are passing activity context in the parameter of the method. This will allow you to use the method in different activities of your application just by passing Activity’s context.
Next we need to get instance of Wifi System Service. To do this we will call getSystemService() method which is available under Activity context.
WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);
By default method will return Boolean false value. It will check the state of Wifi using isWifiEnabled() method.
if(wifiManager.isWifiEnabled())
If the it WiFi is enabled then it try disabling the it using setWifiEnabled(false) method with false parameter.
setWifiEnabled() method accepts Boolean values. If false is passed it will turn off the Wifi and if true is passed it will turn on the WiFi.
The complete condition will be as following
if(wifiManager.isWifiEnabled()){ if(wifiManager.setWifiEnabled(false)) return true; }else{ if(wifiManager.setWifiEnabled(true)) return true; } return false;
public boolean toggleWIFI(Context mContext) { WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE); if(wifiManager.isWifiEnabled()){ if(wifiManager.setWifiEnabled(false)) return true; }else{ if(wifiManager.setWifiEnabled(true)) return true; } return false; }