我想构建一个应用程序,检查所有可用的WiFi网络,
如果网络的SSID与搜索密钥匹配,则连接到该网络,如果两个网络匹配,则连接到信号强度较高的网络。
e.g。 SearchKey ="打开";
这里是检查所有wifi名称的代码:
if (networkInfo.isConnected()) {
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
List<ScanResult> results = wifiManager.getScanResults();
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
}
然后我需要
Arrays.asList(mItems).contains("Open")
我被困在这里,如何正确检查关键字&#34; Open&#34;退出,如果是这样,那么得到全名并在下面使用。 ?
在线示例如何联系。
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", key);
WifiManager wifiManager = (WifiManager).getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
更新代码------------------------------ - -------------- ------------------- - - ---------------------------- -----------
如何检查,这有效但现在我需要实现按信号强度搜索
if (!result.SSID.isEmpty()) {
String key = result.SSID + " " + result.capabilities;
Log.i("TAG", "ssid: " + result.SSID + " | level: " + result.level);
if(result.SSID.contains("Open")) {
String useSSID = result.SSID;
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
现在我如何查询我的:
ArrayList<ScanResult> mItems = new ArrayList<ScanResult>();
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) > calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
}
}
if(mItems.contains("Open")) {
String useSSID = mItems #how to the name SSID name from mItems ???
Log.w(TAG, "useSSID => " + useSSID);
connectToWifi(MainActivity.this, useSSID);
break;
}
else { Log.e(TAG, "NO result contains"); }
=== 现在我的问题是如何从mItems中获取SSID名称? 谢谢你的帮助。
答案 0 :(得分:2)
以下是相同的摘录:
public string getValidSSID()
{
List<ScanResult> results = wifiManager.getScanResults();
HashMap<String,ScanResult> distinctNetworks = new HashMap<String, ScanResult>();
for(ScanResult scanResult : results)
{
if(scanResult.SSID.contains("Open"))
{
if(!distinctNetworks.containsKey(scanResult))
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
else
{
if(WifiManager.compareSignalLevel(scanResult.level, distinctNetworks.get(scanResult.SSID).level)>0)
{
distinctNetworks.put(scanResult.SSID, scanResult);
}
}
}
}
Set<String> networks = distinctNetworks.keySet();// This will only contain one key which will be ths ssid with the max strength containing "open" in SSID
for (String s : networks) {
return s;
}
}