1、需要在AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
根据android系统不同,还需要添加和申请定位权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
否则的话,wifiManager.getScanResults()获取不到任何的数据;
2、请先将android设置开启WLAN
private void startScanWifi() {WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);wifiManager.startScan();List<ScanResult> resultList = wifiManager.getScanResults();ScanResult scanResult;String SSID;int rssi;int level;if (resultList != null && resultList.size() > 0) {for (int i = 0; i < resultList.size(); i++) {scanResult = resultList.get(i);//名称SSID = scanResult.SSID;//信号强度,得到的值是一个0到-100的区间值,是一个int型数据rssi = scanResult.level;//信号强度等级,根据强度值,分为6个等级,5最大,表示强度最高level = WifiManager.calculateSignalLevel(rssi, 6);}}}
resultList就是可连接的wifi列表结果
3、获取已连接的wifi
private WifiResultInfo getConnectedWifi() {WifiResultInfo wifiResultInfo = null;WifiInfo wifiInfo = wifiManager.getConnectionInfo();if (wifiInfo != null) {String ssid = wifiInfo.getSSID();int rssi = wifiInfo.getRssi();if(ssid.startsWith("\"") && ssid.endsWith("\"")){ssid = ssid.substring(1, ssid.length() - 1);}}return wifiResultInfo;}