Android: 如何以编程方式启用/禁用 Wifi 或 Internet 连接

使用连接管理器类,我们可以访问 wifi 或 Internet 网络:

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 ) {
// ...
}

其中 01分别是指移动和 wifi 连接

如果我的 Android 设备连接到这两个网络,我们可以在任何一个网络之间切换,或者禁用任何一个网络?比如使用函数:

connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
159908 次浏览

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"/>

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

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"/>

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.

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

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.

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

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*/ }
}

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" />

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);
}