. . .

Toggle WiFi Method in Android

Published: November 28, 2012

On This Page

    First 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;
    
     Following is the complete method 
    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;
    }

     

    Don't forget to share this post

      Let's Build Digital Excellence Together


      • Cost Efficient Solutions.
      • Minimal Timelines.
      • Effective Communication.
      • High Quality Standards.
      • Lifetime Support.
      • Transparent Execution.
      • 24/7 Availability.
      • Scalable Teams.

      Join Our 200+ Happy Clients Across Globe


      Free Consultation.

        Do you need tech help of your startup/business? Experts from our team will get in touch with you.

        Please do not post jobs/internships inquiries here.