android 实现指定wifi切换 ,网上找了很多代码都有问题,借鉴其他人的整理了一份。


操作过程中发现始终切换失败,最终发现是密码问题。所连接设备虽然不需要密码,但这里连接时需要指定一个空密码


使用办法:



wifiUtils = new WifiUtils(CurrentStatusActivity.this);
		boolean isEnable = wifiUtils.isEnable();
		if (isEnable) {
			// wifi已经打开
			if (dialog != null) {
//关闭加载窗口
				dialog.dismiss();
			}
			// 是否已经连接上了 指定前缀的wifi
			if (wifiUtils.getSSID().contains(WifiUtils.wifi_ssid_suffix)) {
//进行操作
} else {
				// 1: 判断当前网络中有几个指定前缀的ssid
				List<String> exsits = wifiUtils.getExistZXwifi();
				if (exsits.size() == 0) {
					//当前网络中没有指定wifi
				} else if (exsits.size() == 1) {
//正确逻辑,写自己的的逻辑代码
				} else {
//当前网络中有多个指定前缀ssid的 wifi ,提示框 提示用户选择。
wifi_dialog = new WifiSwitchDialog(this, exsits);
					wifi_dialog.show();
				}
			}
		} else {
			// wifi 未打开
			// 网络不可用,打开网络设置页面
			dialog = new NetSetingDialog(this);
			dialog.show();
		}





import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;

/**
 * wifi 操作
 * 
 * @author java_developer
 * 
 */
public class WifiUtils {

	public static String wifi_ssid_suffix = "Tp-link";

	// 定义WifiManager对象
	private WifiManager mWifiManager;
	// 定义WifiInfo对象
	private WifiInfo mWifiInfo;
	// 扫描出的网络连接列表
	private List<ScanResult> mWifiList;

	// 定义一个WifiLock
	WifiLock mWifiLock;

	// 构造器
	public WifiUtils(Context context) {
		// 取得WifiManager对象
		mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		// 取得WifiInfo对象
		mWifiInfo = mWifiManager.getConnectionInfo();
	}

	// 打开WIFI
	public boolean openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			return mWifiManager.setWifiEnabled(true);
		} else {
			return true;
		}
	}

	// 关闭WIFI
	public void closeWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	public boolean isEnable() {
		return mWifiManager.isWifiEnabled();
	}

	// 检查当前WIFI状态
	public int checkState() {
		return mWifiManager.getWifiState();
	}

	// 锁定WifiLock
	public void acquireWifiLock() {
		mWifiLock.acquire();
	}

	// 解锁WifiLock
	public void releaseWifiLock() {
		// 判断时候锁定
		if (mWifiLock.isHeld()) {
			mWifiLock.acquire();
		}
	}

	// 创建一个WifiLock
	public void creatWifiLock() {
		mWifiLock = mWifiManager.createWifiLock("Test");
	}

	// 得到配置好的网络
	public List<WifiConfiguration> getConfiguration() {
		return mWifiConfiguration;
	}

	// 指定配置好的网络进行连接
	public void connectConfiguration(int index) {
		// 索引大于配置好的网络索引返回
		if (index > mWifiConfiguration.size()) {
			return;
		}
		// 连接配置好的指定ID的网络
		mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
	}

	// 得到网络列表
	public List<ScanResult> getWifiList() {
		return mWifiList;
	}

	// 查看扫描结果
	public StringBuilder lookUpScan() {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < mWifiList.size(); i++) {
			stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
			// 将ScanResult信息转换成一个字符串包
			// 其中把包括:BSSID、SSID、capabilities、frequency、level
			stringBuilder.append((mWifiList.get(i)).toString());
			stringBuilder.append("/n");
		}
		return stringBuilder;
	}

	// 得到MAC地址
	public String getMacAddress() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
	}

	// 得到接入点的BSSID
	public String getBSSID() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
	}

	public String getSSID() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
	}

	// 得到IP地址
	public int getIPAddress() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
	}

	// 得到连接的ID
	public int getNetworkId() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
	}

	// 得到WifiInfo的所有信息包
	public String getWifiInfo() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
	}

	/**
	 * 简介:wifi结合
	 * 
	 */
	public int switchWifi(String wifi_ssid) {
		String ssid = this.getSSID();
		ssid = ssid.replace("\"", "");
		if (ssid.contains(wifi_ssid)) {
			// wifi已经加入相应wifi无需进行切换
			// ping 是否通
			boolean ping = new Tools().ping("2");
			if (ping) {
				return 0;
			} else {
				// 虽然加入了网络,但是网络不通
				return 4;
			}
		} else {
			// 首先判断当前wifi列表中是否有zx_wifr
			WifiConfiguration tempConfig = this.IsExsits(wifi_ssid);
			if (tempConfig != null) {
				mWifiManager.removeNetwork(tempConfig.networkId);
			}
			// 进行切换
			WifiConfiguration wcg = this.createWifiInfo(wifi_ssid,"", 1);
			boolean success = this.addNetwork(wcg);
			if (success) {
				return 1;
			} else {
				return 2;
			}
		}
	}

	// 添加一个网络并连接
	public boolean addNetwork(WifiConfiguration wcg) {
		int wcgID = mWifiManager.addNetwork(wcg);
		// 执行命令去连接
		boolean b = mWifiManager.enableNetwork(wcgID, true);
		mWifiManager.saveConfiguration();
		return b;
	}

	// 断开指定ID的网络
	public void disconnectWifi(int netId) {
		mWifiManager.disableNetwork(netId);
		mWifiManager.disconnect();
	}

	// 然后是一个实际应用方法,只验证过没有密码的情况:
	/**
	 * 第一参数是SSID的名称;第二个参数是指定SSID网络的密码,当不需要密码是置空(”“);第三个参数是热点类型:1-无密码 /
	 * 2-WEP密码验证(未测试)/ 3-WAP或WAP2 PSK密码验证。
	 * 
	 * @param SSID
	 * @param Password
	 * @param Type
	 * @return
	 */
	public WifiConfiguration createWifiInfo(String wifi_ssid,String Password, int Type) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + wifi_ssid + "\"";

		if (Type == 1) {
			// WIFICIPHER_NOPASS
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 2) {
			// WIFICIPHER_WEP
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 3) {
			// 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;
	}

	// 网络连接列表
	private List<WifiConfiguration> mWifiConfiguration;

	public void startScan() {
		mWifiManager.startScan();
		// 得到扫描结果
		mWifiList = mWifiManager.getScanResults();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
	}

	public List<String> getExistZXwifi() {
		List<String> wifis = new ArrayList<String>();
		List<ScanResult> mWifiList = mWifiManager.getScanResults();
		for (int i = 0; i < mWifiList.size(); i++) {
			ScanResult sr = mWifiList.get(i);
			String s_ssid = sr.SSID;
			if (s_ssid.contains(wifi_ssid_suffix)) {
				wifis.add(s_ssid);
			}
		}
		return wifis;
	}

	private WifiConfiguration IsExsits(String SSID) {
		if (mWifiManager == null) {
			return null;
		} else {
			List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
			for (int i = 0; i < existingConfigs.size(); i++) {
				WifiConfiguration existingConfig = existingConfigs.get(i);
				String c_ssid = existingConfig.SSID;
				if (c_ssid.contains(SSID)) {
					return existingConfig;
				}
			}
		}
		return null;
	}
}