Android: How to Enable/Disable Wifi or Internet Connection Programmatically
Asked Answered
B

10

90

Using the Connectivity Manager Class we can get access to either wifi or Internet Network:

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
  connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
  // ...
}

where 0 and 1 respectively refers to mobile and wifi connection

If my Android device is connected to both, can we switch between any of the networks or can we disable any of the networks? Like using a function:

connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
Betthezel answered 14/10, 2010 at 7:28 Comment(1)
Did you get any solution for mobile data disable option ?Nomen
D
187

I know of enabling or disabling wifi:

WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(status);

where status may be true or false as per requirement.

Edit:

You also need the following permissions in your manifest file:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> 
Dukedom answered 14/10, 2010 at 7:45 Comment(6)
Also at manifest: <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />Komatik
Does this differ from wifiManager.reconnect()? What about wifiManager.reassociate()? Also in the approach above if you wanted to reset the WiFi could you call wifiManager.setWifiEnabled(false) and wifiManager.setWifiEnabled(true) back to back? Or would you have to disable it first, then wait for some signal (broadcast receiver etc.) before enabling it again?Dinsdale
If you want demo tutorial fot then its here : demoadda.com/demo/android/…Ulceration
“<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />” is also needed.Acus
Is it possible to control WiFi in M device from Application?Abvolt
Deprecated in API level 29. See BigSt's answer.Cravens
S
32

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE
Shrinkage answered 10/9, 2012 at 5:7 Comment(3)
only CHANGE_WIFI_STATE is necessary, at least in Android 4.2Kean
UPDATE_DEVICE_STATS is only for system appsBisexual
From Android Q , you can not be directly on/off the wifiVariable
C
12

A complete solution:

try {
    WifiManager wifi = (WifiManager) 
        context.getSystemService(Context.WIFI_SERVICE);

    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = "\"SSIDName\"";
    wc.preSharedKey  = "\"password\"";
    wc.hiddenSSID = true;
    wc.status = WifiConfiguration.Status.ENABLED; 

    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

    wc.allowedPairwiseCiphers
        .set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers
        .set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    boolean b=wifi.isWifiEnabled();
    if (b) {
        wifi.setWifiEnabled(false);
        Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show();
    } else {
        wifi.setWifiEnabled(true);
        Toast.makeText(context, "no", Toast.LENGTH_SHORT).show();
    }
    //Log.d("WifiPreference", "enableNetwork returned " + b );

} catch (Exception e) {
    e.printStackTrace();
}

Reference: http://amitkumar-android.blogspot.com/p/installation-steps.html

Cohdwell answered 5/1, 2011 at 19:57 Comment(3)
The call to set the wifi manager with the wifi configuration is missing: wifi.addNetwork(wc);Gluttonize
Why would you hard-code your SSID and password? Not a good idea.Precambrian
@Precambrian I think it's only for the purpose of demonstration.Educatory
O
11

In Android Q (Android 10) you can't enable/disable wifi programmatically anymore. Use Settings Panel to toggle wifi connectivity:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    // can also use `Settings.Panel.ACTION_WIFI` to enable/disable only WiFi
    val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
    startActivityForResult(panelIntent, 0)
} else {
    // use previous solution, add appropriate permissions to AndroidManifest file (see answers above)
    (this.context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}
Observer answered 18/4, 2020 at 13:4 Comment(2)
Settings.Panel official docsCravens
Found this helpfullDowntoearth
N
4

To enable disable Wifi use the WifiManager class to get system(android device) services for Wifi :

WifiManager wifi =(WifiManager)getSystemService(Context.WIFI_SERVICE); 

Now the object wifi of the WifiManager class is used to get the wifi status:

if(wifi.isWifiEnabled())
    //Perform Operation
else
    //Other Operation

And most importantly do not forget to give the following permission in your Android Manifest File:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

To get detailed info and full sample code of the project for enable/disable Wifi on android visit my website link.

Nellanellda answered 14/6, 2012 at 21:4 Comment(0)
F
3

This method is deprecated now from now starting with Android Q.

Try This will really help.

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {// if build version is less than Q try the old traditional method
                    if (!wifiManager.isWifiEnabled()) {
                        wifiManager.setWifiEnabled(true);
                        btnOnOff.setText("Wifi ONN");
                    } else {
                        wifiManager.setWifiEnabled(false);
                        btnOnOff.setText("Wifi OFF");
                    }
                } else {// if it is Android Q and above go for the newer way    NOTE: You can also use this code for less than android Q also
                    Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
                    startActivityForResult(panelIntent, 1);
                }
Fonville answered 26/6, 2020 at 15:28 Comment(1)
Worth pointing to new/preferred method with example?Malines
G
1

add this permission in your manifest and than use the above code to change WiFi state:

 <!--permission ge enable and disable WIFI in android-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
Gath answered 18/5, 2012 at 7:29 Comment(0)
B
1

I could not access the context object directly.
My solution is as following:

Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
wifiManager.SetWifiEnabled(state);

Also I had to change some writings eg. WIFI_SERVICE vs. WifiService.

Barros answered 17/5, 2018 at 12:30 Comment(0)
R
1

It is possible to enable/disable wifi on pre Android 10 devices using the following code:

WifiManager wifiManager = 
(WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);

wifiManager.setWifiEnabled(status);

But note that it is not possible to do this anymore on Android 10 and probably going ahead as well.
https://issuetracker.google.com/issues/141011684

Reflex answered 25/9, 2019 at 7:40 Comment(0)
C
1

Android 10 (Q) onwards wifi can not be enabled/disabled you need to open the setting intent,

// for android Q and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Intent panelIntent = new 
Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY);
            startActivityForResult(panelIntent, 0);
        } else {
            // for previous android version
            WifiManager wifiManager = (WifiManager) 
this.getApplicationContext().getSystemService(WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }

In manifest,

 <uses-permission
    android:name="android.permission.CHANGE_WIFI_STATE"
    android:required="true" />
Connally answered 5/6, 2020 at 3:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.