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

发布于 2024-09-27 21:30:16 字数 572 浏览 14 评论 0原文

使用连接管理器类,我们可以访问 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);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

暮色兮凉城 2024-10-04 21:30:16

我知道启用或禁用 wifi:

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

根据要求,状态可能为 truefalse

编辑:

您的清单文件中还需要以下权限:

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

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"/> 
懒的傷心 2024-10-04 21:30:16

启用 WiFi:

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

禁用 WiFi:

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

注意:
要使用 WiFi 状态进行访问,我们必须在 AndroidManifest.xml 文件中添加以下权限:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

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
笔落惊风雨 2024-10-04 21:30:16

完整的解决方案:

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

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

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

蘑菇王子 2024-10-04 21:30:16

Android Q (Android 10) 中,您无法再以编程方式启用/禁用 wifi。使用设置面板切换 WiFi 连接:

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

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*/ }
}
遥远的绿洲 2024-10-04 21:30:16

要启用禁用 Wifi,请使用 WifiManager 类获取 Wifi 的系统(android 设备)服务:

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

现在使用 WifiManager 类的对象 wifi获取 wifi 状态:

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

最重要的是,不要忘记在 Android 清单文件中授予以下权限:

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

要获取在 Android 上启用/禁用 Wifi 的项目的详细信息和完整示例代码,请访问 我的网站链接

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.

浮生未歇 2024-10-04 21:30:16

从 Android Q 开始,此方法已被弃用

。尝试一下会很有帮助。

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

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);
                }
温柔少女心 2024-10-04 21:30:16

在您的清单中添加此权限,然后使用上面的代码更改 WiFi 状态:

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

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"/>
双马尾 2024-10-04 21:30:16

我无法直接访问上下文对象。
我的解决方案如下:

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

我还必须更改一些著作,例如。 WIFI_SERVICE 与 WifiService。

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.

扶醉桌前 2024-10-04 21:30:16

可以使用以下代码在 Android 10 之前的设备上启用/禁用 wifi:

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

wifiManager.setWifiEnabled(status);

请注意,在 Android 10 上不再可能执行此操作,并且可能也会继续执行此操作。
https://issuetracker.google.com/issues/141011684

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

沩ん囻菔务 2024-10-04 21:30:16

Android 10(Q)以上的wifi无法启用/禁用您需要打开设置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);
        }

在manifest中,

 <uses-permission
    android:name="android.permission.CHANGE_WIFI_STATE"
    android:required="true" />

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" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文