Android:如何以编程方式启用/禁用Wifi或Internet连接使用Connectivity Manager Class,我们可以访问wifi或Internet网络:ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);// ARE WE CONNECTED TO THE NETif ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
// ...}其中0和1分别指移动和wifi连接如果我的Android设备连接到两者,我们可以在任何网络之间切换,还是可以禁用任何网络?喜欢使用功能:connec.getNetworkInfo(0).setState(NetworkInfo.State.DISCONNECTED);
3 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
我知道启用或禁用wifi:
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);wifiManager.setWifiEnabled(status);
状态可能是true
或false
根据要求。
编辑:
您还需要清单文件中的以下权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
人到中年有点甜
TA贡献1895条经验 获得超7个赞
启用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
精慕HU
TA贡献1845条经验 获得超8个赞
完整的解决方案:
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
- 3 回答
- 0 关注
- 2154 浏览
添加回答
举报
0/150
提交
取消