2.2)创建和管理Wi-Fi连接和配置
使用WiFi Manager可以进行网络配置,控制连接到哪个网络。当连接建立后,可以进一步获取活动网络连接的额外配置信息。使用函数getConfiguredNetworks可获得当前网络配置信息的列表,返回值是WifiConfiguration对象,包含了网络ID、SSID和其他配置信息。
要使用某一网络连接,可使用enableNetwork函数,传入网络ID并设置disableAllOthers参数为true即可,代码片段如下:
// Get a list of available configurationsList<WifiConfiguration> configurations = wm.getConfiguredNetworks();// Get the network ID for the first oneif (configurations.size() > 0) {int netID = configurations.get(0).networkId;// Enable the networkboolean disableAllOthers = true;wm.enableNetwork(netID, disableAllOthers);} 一旦连接建立,就可以使用getConnectionInfo函数来返回连接的状态,返回的是WifiInfo对象,包含了当前接入点的BSSID、Mac地址、IP地址,以及当前链路速度和信号强度。
下面的代码片段用于查询当前活动Wi-Fi连接并显示获取的相关信息:
WifiInfo info = wm.getConnectionInfo();if (null != info.getBSSID()) {int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);int speed = info.getLinkSpeed();String units = WifiInfo.LINK_SPEED_UNITS;String ssid = info.getSSID();String toastText = String.format("Connected to {0} at {1}{2}. Strength {3}/5", ssid, speed, units, strength);Toast.makeText(this.getApplicationContext(), toastText, Toast.LENGTH_LONG);}
2.3)扫描Wifi热点
我们可以使用startScan函数进行Wifi接入点的扫描,当扫描结束且结果可用时,WifiManager将发送SCAN_RESULTS_AVAILABLE_ACTIONL类型的intent。使用getScanResults函数可以获取扫描的结果信息,并保存中ScanResult对象中。ScanResult对象中存放了检测到的每个接入点的详细信息,包括链路速度、信号强度、SSID和支持的认证技术。下面代码片段显示了Wifi热点扫描的过程:
// Register a broadcast receiver that listens for scan resultsregisterReceiver(new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {List<ScanResult> results = wifi.getScanResults();ScanResult bestSignal = null;for (ScanResult result : results) {if (null == bestSignal ||WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0) {bestSignal = result;}}String toastText = String.format("{0} networks found. {1} is the strongest.", results.size(), bestSignal.SSID);Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_LONG);}}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));//Initiate a scanwifi.startScan();