使用WifiManager和ScanResult进行Wifi操作

Wifi那部分的应用,在开发中也很少会用到,碰巧之前就遇到了。
Wifi上分为几部分:
1 获取周围的热点;
2 标识出取到的热点的加密方法;
3 连接不加密Wifi,手动输入有密码的Wifi;
4 保存连接好的Wifi到系统中;

一共四部分;
用到Wifi部分的接口有:
android.net.wifi.WifiManager类;

接收Wifi的反馈,并没有找到系统提供的接口,这里使用的是通过接收不同的广播来进行判断wifi的连接结果;

private WifiManager mWifiManager;
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);


然后接着使用的是:

打开Wifi:

mWifiManager.setWifiEnabled(true);


同理关闭Wifi也是这个接口;

打开Wifi的同时,系统会默认去遍历已经连接过的Wifi热点,进行连接,这部分连接工作都是交给系统完成即可;

启动Wifi热点列表扫描。
mWifiManager.startScan();

那么它的结果呢,就是在广播接收器中调用:
List scanResult = mWifiManager.getScanResults();
进行获取扫描结果;

接着分为对有密码的wifi连接和对无密码的wifi进行连接:

private void connectWifi(){
	WifiConfiguration wifiConfig;
	wifiConfig = wifiHelper.setWifiParams("TP-LINK_2.4GHz_F983");
	// 连接没有密码的Wifi热点如下
	// wifiConfig = wifiHelper.setWifiParamsNoPassword("TP-LINK_2.4GHz_F982");
	int wcgID = mWifiManager.addNetwork(wifiConfig);
	boolean flag = mWifiManager.enableNetwork(wcgID, true);
	textView.setText("启动连接:" + flag + "\n");
}

//其中调用函数如下进行有密码Wifi连接:

public WifiConfiguration setWifiParams(String ssid) {
	String gol_password = "123456789";
	WifiConfiguration apConfig = new WifiConfiguration();
	apConfig.SSID = "\"" + ssid + "\"";
	apConfig.preSharedKey = "\"" + gol_password + "\"";
	apConfig.hiddenSSID = true;
	apConfig.status = WifiConfiguration.Status.ENABLED;
	apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
	apConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
	apConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
	apConfig.allowedPairwiseCiphers
			.set(WifiConfiguration.PairwiseCipher.TKIP);
	apConfig.allowedPairwiseCiphers
			.set(WifiConfiguration.PairwiseCipher.CCMP);
	apConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
	return apConfig;
}

//其中调用函数如下进行无密码Wifi连接:

public WifiConfiguration setWifiParamsNoPassword(String ssid) {
	String SSID = ssid;
	WifiConfiguration config = new WifiConfiguration();
	config.allowedAuthAlgorithms.clear();
	config.allowedGroupCiphers.clear();
	config.allowedKeyManagement.clear();
	config.allowedPairwiseCiphers.clear();
	config.allowedProtocols.clear();
	config.SSID = "\"" + SSID + "\"";
	// 没有密码,一定要注释这两个值
	// config.wepKeys[0] = "";
	// config.wepTxKeyIndex = 0;

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

	// WifiManager wifiManager = (WifiManager)
	// mContext.getSystemService(Context.WIFI_SERVICE);
	// wifiManager.enableNetwork(wifiManager.addNetwork(config), true);

	return config;
}


保存某个Wifi热点,重启后系统或者重启Wifi后自动连接:

// 保存到系统中,重启后有效

mWifiManager.saveConfiguration();

这样是保存所有的连接情况,也可以说是当前的情况,因为当前就是连接了一个热点;

删除某个已经保存好的Wifi热点:

List existingConfigs;
existingConfigs= wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
	if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
		mWifiManager.removeNetwork(existingConfig.networkId);
	}
}

获取当前连接好的Wifi热点:

private String getCurrentWifi(){
	WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
	int wifiState = wifiMgr.getWifiState();
	WifiInfo info = wifiMgr.getConnectionInfo();
	String ssid = info != null ? info.getSSID() : "null";
	String state = "";
	switch (wifiState) {
	case 0:
		state = "WIFI_STATE_DISABLING";
		break;

	case 1:
		state = "WIFI_STATE_DISABLED";
		break;
	case 2:
		state = "WIFI_STATE_ENABLING";
		break;
	case 3:
		state = "WIFI_STATE_ENABLED";
		break;
	case 4:
		state = "WIFI_STATE_UNKNOWN";
		break;
	default:
		break;
	}
	btn_currentWifiName.setText("当前wifi:[" + ssid + "](" + state + ")");
	return ssid;
}

下面着重看一下Wifi列表的获取和连接状态和验证返回结果:
获取结果:
textView.setText("扫描到的wifi列表\n");
if (scanResult == null) {
Toast.makeText(getApplicationContext(), "扫描列表为空",Toast.LENGTH_SHORT).show();
textView.append("\n扫描列表为空");
return;
}
for (int i = 0; i < scanResult.size(); i++) {
textView.append(scanResult.get(i).SSID + ":"+ getEncryption(scanResult.get(i)) + "\n");
}

private String getEncryption(ScanResult scanResult) {
	if (!TextUtils.isEmpty(scanResult.SSID)) {
		String capabilities = scanResult.capabilities;
		Log.i("hefeng", "[" + scanResult.SSID + "]" + capabilities);

		if (!TextUtils.isEmpty(capabilities)) {

			if (capabilities.contains("WPA")
					|| capabilities.contains("wpa")) {
				Log.i("hefeng", "wpa");
				return "wpa";
			} else if (capabilities.contains("WEP")
					|| capabilities.contains("wep")) {
				Log.i("hefeng", "wep");
				return "wep";
			} else {
				Log.i("hefeng", "no");
				return "no password";
			}
		}
	}

	return scanResult.capabilities.toString();
}

接下来是Wifi广播的情况了:

//注册:
private void wifiRegister(){
	IntentFilter filter = new IntentFilter();
	// filter.addAction(WifiManager.ERROR_AUTHENTICATING);
	filter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
	filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
	filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
	filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
	// 测试wifi验证密码错误问题
	filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
	registerReceiver(new WifiReceiver(), filter);
}

//接收:
class WifiReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		scanResult = mWifiManager.getScanResults();
		String action = intent.getAction();
		textView.append(action);
		Log.i("WifiReceiver", action);
		// / Wifi 状态变化
		if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
			WifiInfo info = mWifiManager.getConnectionInfo();
			SupplicantState state = info.getSupplicantState();
			if (state == SupplicantState.COMPLETED) {
				textView.append("(验证成功)");
				Log.i("WifiReceiver", "(验证成功)");
			}
			int errorCode = intent.getIntExtra(
					WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
			if (errorCode == WifiManager.ERROR_AUTHENTICATING) {
				textView.append("(验证失败)");
				Log.i("WifiReceiver", "(验证失败)");
			}
		}
		textView.append("\n");
	}
}
接收到的广播不是一次接收,而已多次接收到Wifi的状态情况:

大体如下:

验证成功的输出Log:

01-01 00:22:38.970: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.440: I/WifiReceiver(5515): android.net.wifi.SCAN_RESULTS
01-01 00:22:41.450: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.460: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.770: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.880: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.880: I/WifiReceiver(5515): (验证成功)
01-01 00:22:41.930: I/WifiReceiver(5515): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:22:41.940: I/WifiReceiver(5515): (验证成功)
01-01 00:22:44.890: I/WifiReceiver(5515): android.net.wifi.RSSI_CHANGED
01-01 00:22:45.580: I/WifiReceiver(5515): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:22:45.590: I/WifiReceiver(5515): android.net.conn.CONNECTIVITY_CHANGE


验证失败的输出Log:

01-01 00:20:53.800: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:20:56.060: I/WifiReceiver(5249): android.net.wifi.SCAN_RESULTS
01-01 00:20:56.320: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:20:56.350: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:20:56.810: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:03.230: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:03.240: I/WifiReceiver(5249): (验证失败)
01-01 00:21:03.330: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:04.610: I/WifiReceiver(5249): android.net.wifi.SCAN_RESULTS
01-01 00:21:06.710: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:21:07.230: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:21:08.120: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:21:21.820: I/WifiReceiver(5249): android.net.wifi.SCAN_RESULTS
01-01 00:21:21.870: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:22.270: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:22.540: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:28.780: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:28.780: I/WifiReceiver(5249): (验证失败)
01-01 00:21:28.860: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:30.160: I/WifiReceiver(5249): android.net.wifi.SCAN_RESULTS
01-01 00:21:30.200: I/WifiReceiver(5249): android.net.wifi.supplicant.STATE_CHANGE
01-01 00:21:32.240: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:21:32.760: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE
01-01 00:21:33.680: I/WifiReceiver(5249): android.net.conn.CONNECTIVITY_CHANGE


最后的最后,贴上使用到的权限:






原创博客来自CSDN:http://blog.csdn.net/dreamintheworld/article/details/45064535


你可能感兴趣的:(Android进阶)