首页 > 学院 > 开发设计 > 正文

检测wifi是否开启,连接指定wifi

2019-11-09 14:38:30
字体:
来源:转载
供稿:网友

首先,想要控制手机wifi状态,必须获得权限,我们需要在清单文件中添加权限;

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"></uses-permission><!-- 允许程序改变网络链接状态 --> <uses-permission android:name="android.permission.access_WIFI_STATE"></uses-permission><!--允许程序访问访问WIFI网络状态信息 --> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission><!-- 允许程序改变WIFI链接状态 -->

我们创建一个wifi管理的工具类:

package com.xiao.androidzhujie;import android.content.Context;import android.net.wifi.WifiConfiguration;import android.net.wifi.WifiManager;import android.text.TextUtils;import android.util.Log;import java.util.List;/** * Created by 燕潇洒 on 2017/2/9. * 打开wifi,并且连接指定wifi */public class WifiAutoConnectManager { PRivate static final String TAG = WifiAutoConnectManager.class.getSimpleName(); WifiManager wifiManager; // 定义几种加密方式,一种是WEP,一种是WPA,还有没有密码的情况 public enum WifiCipherType { /** * WEP(有线等效加密)——采用WEP 64位或者128位数据加密。 */ WIFICIPHER_WEP, /** * WPA-PSK [TKIP]——采用预共享密钥的Wi-Fi保护访问,采用WPA-PSK标准加密技术,加密类型为TKIP。 * WPA2-PSK [AES]——采用预共享密钥的Wi-Fi保护访问(版本2),采用WPA2-PSK标准加密技术,加密类型为AES。 * WPA-PSK [TKIP] + WPA2-PSK [AES]——允许客户端使用WPA-PSK [TKIP]或者WPA2-PSK [AES]。 */ WIFICIPHER_WPA, /** * 没有密码 */ WIFICIPHER_NOPASS, WIFICIPHER_INVALID } // 构造函数 public WifiAutoConnectManager(WifiManager wifiManager) { this.wifiManager = wifiManager; } // 构造函数 public WifiAutoConnectManager(Context context) { this.wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); } /** * 提供一个外部接口,传入要连接的无线网 * @param ssid WIFI无线网络的名称 * @param passWord WIFI网络密码 * @param type WIFI类型() */ public void connect(String ssid, String password, WifiCipherType type) { Thread thread = new Thread(new ConnectRunnable(ssid, password, type)); thread.start(); } // 查看以前是否也配置过这个网络 private WifiConfiguration isExsits(String SSID) { List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("/"" + SSID + "/"")) { return existingConfig; } } return null; } private WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type) { System.out.println("获得通知连接wifi"+SSID+Password); //配置wifi网络 WifiConfiguration config = new WifiConfiguration(); //此配置支持的身份验证协议集 config.allowedAuthAlgorithms.clear(); //分组密码支持的配置设置 config.allowedGroupCiphers.clear(); //该配置支持的密钥管理协议集 config.allowedKeyManagement.clear(); //该配置支持WPA两两密码设置 config.allowedPairwiseCiphers.clear(); //此配置支持的安全协议集 config.allowedProtocols.clear(); config.SSID = "/"" + SSID + "/""; // 没有密码 if (Type == WifiCipherType.WIFICIPHER_NOPASS) { config.wepKeys[0] = ""; config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; } // wep加密 if (Type == WifiCipherType.WIFICIPHER_WEP) { if (!TextUtils.isEmpty(Password)) { if (isHexWepKey(Password)) { config.wepKeys[0] = Password; } else { config.wepKeys[0] = "/"" + Password + "/""; } } config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.wepTxKeyIndex = 0; } // wpa加密 if (Type == WifiCipherType.WIFICIPHER_WPA) { config.preSharedKey = "/"" + Password + "/""; config.hiddenSSID = true; config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); // 此处需要修改否则不能自动重联 // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); config.status = WifiConfiguration.Status.ENABLED; } return config; } // 打开wifi功能 private boolean openWifi() { boolean bRet = true; if (!wifiManager.isWifiEnabled()) { bRet = wifiManager.setWifiEnabled(true); System.out.println("wifi没有打开,执行打开!"); } System.out.println("wifi已经打开"); return bRet; } class ConnectRunnable implements Runnable { //wifi名称 private String ssid; //wifi密码 private String password; //加密类型 private WifiCipherType type; public ConnectRunnable(String ssid, String password, WifiCipherType type) { this.ssid = ssid; this.password = password; this.type = type; } @Override public void run() { // 打开wifi openWifi(); // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右),所以要等到wifi // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句 while (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) { try { // 为了避免程序一直while循环,让它睡个100毫秒检测…… Thread.sleep(100); } catch (InterruptedException ie) { } } WifiConfiguration wifiConfig = createWifiInfo(ssid, password, type); // if (wifiConfig == null) { Log.d(TAG, "wifiConfig is null!"); return; } WifiConfiguration tempConfig = isExsits(ssid); if (tempConfig != null) { wifiManager.removeNetwork(tempConfig.networkId); } int netID = wifiManager.addNetwork(wifiConfig); boolean enabled = wifiManager.enableNetwork(netID, true); Log.d(TAG, "enableNetwork status enable=" + enabled); boolean connected = wifiManager.reconnect(); Log.d(TAG, "enableNetwork connected=" + connected); } } private static boolean isHexWepKey(String wepKey) { final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } private static boolean isHex(String key) { for (int i = key.length() - 1; i >= 0; i--) { final char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; }}

由于,此工具类是本人搜索获得,目前正在思考每一块的功能,这里先给大家贴出代码,后面再做详细解释. 最后,我们在Activity中使用它:工具类中有两个构造函数,我们可以任选一个。 获取wifiManager服务:

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

然后调用下面方法中的任意一个,如果使用第一种方法,需要传入WifiManager对象,如果选择第二种,只需要传入上下文即可:

/** * 打开并连接指定wifi */ public void sendMsgOp(){ WifiAutoConnectManager wifiAutoConnectManager = new WifiAutoConnectManager(wifiManager); wifiAutoConnectManager.connect("theten52","1122334452", WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA); System.out.println("获得通知连接wifi"); } /** * 打开并连接指定wifi */ public void sendMsgOp(String... args){ WifiAutoConnectManager wifiAutoConnectManager = new WifiAutoConnectManager(this); wifiAutoConnectManager.connect("theten52","1122334452", WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA); System.out.println("获得通知连接wifi"); }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表