Android - 如何扫描接入点并选择最强信号?

发布于 2024-09-01 18:54:30 字数 2493 浏览 4 评论 0原文

我目前正在尝试在 Android 中编写一个类,它将扫描接入点,计算哪个接入点具有最好的信号,然后连接到该接入点。

因此,该应用程序将能够在移动中扫描并附加到新的接入点。

我可以扫描和计算最佳信号。

但当涉及到连接到最佳接入点时,我遇到了麻烦。

看来,enableNetwork(netid, otherTrueFalse) 是连接到接入点的唯一方法,但这会导致问题,因为从我的扫描结果来看,我无法获取信号最强的接入点的 ID。

这是我的代码:


public void doWifiScan(){

  scanTask = new TimerTask() {
  public void run() {
      handler.post(new Runnable() {
          public void run() {
               sResults = wifiManager.scan(getBaseContext()); 
               if(sResults!=null)
               Log.d("TIMER", "sResults count" + sResults.size());
               ScanResult scan = wifiManager.calculateBestAP(sResults);
               wifiManager.addNewAccessPoint(scan);
           }
       });
    }};

    t.schedule(scanTask, 3000, 30000); 
}

public ScanResult calculateBestAP(List<ScanResult> sResults){

     ScanResult bestSignal = null;
        for (ScanResult result : sResults) {
          if (bestSignal == null
              || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
            bestSignal = result;
        }

        String message = String.format("%s networks found. %s is the strongest. %s is the bsid",
                sResults.size(), bestSignal.SSID, bestSignal.BSSID);

        Log.d("sResult", message);
        return bestSignal;
}

public void addNewAccessPoint(ScanResult scanResult){

    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = '\"' + scanResult.SSID + '\"';
    //wc.preSharedKey  = "\"password\"";
    wc.hiddenSSID = true;
    wc.status = WifiConfiguration.Status.ENABLED;        
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    int res = mainWifi.addNetwork(wc);
    Log.d("WifiPreference", "add Network returned " + res );
    boolean b = mainWifi.enableNetwork(res, false);        
    Log.d("WifiPreference", "enableNetwork returned " + b );

}

当我尝试使用 addNewAccessPoint(ScanResult scanResult) 时,它只是将另一个 AP 添加到设置应用程序中的列表中,其名称与信号最好的 AP 相同,因此我最终会得到大量重复项,但实际上并非如此依附于他们。

谁能指出我更好的解决方案的方向?

I am currently trying to write a class in Android that will Scan for access points, calculate which access point has the best signal and then connect to that access point.

So the application will be able to scan on the move and attach to new access points on the go.

I have the scanning and calculation of the best signal working.

But when it comes to attaching to the best access point I am having trouble.

It appears that enableNetwork(netid, othersTrueFalse) is the only method for attaching to an Access point but this causes problems as from my Scan Results I am not able to get the id of the access point with the strongest signal.

This is my code:


public void doWifiScan(){

  scanTask = new TimerTask() {
  public void run() {
      handler.post(new Runnable() {
          public void run() {
               sResults = wifiManager.scan(getBaseContext()); 
               if(sResults!=null)
               Log.d("TIMER", "sResults count" + sResults.size());
               ScanResult scan = wifiManager.calculateBestAP(sResults);
               wifiManager.addNewAccessPoint(scan);
           }
       });
    }};

    t.schedule(scanTask, 3000, 30000); 
}

public ScanResult calculateBestAP(List<ScanResult> sResults){

     ScanResult bestSignal = null;
        for (ScanResult result : sResults) {
          if (bestSignal == null
              || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
            bestSignal = result;
        }

        String message = String.format("%s networks found. %s is the strongest. %s is the bsid",
                sResults.size(), bestSignal.SSID, bestSignal.BSSID);

        Log.d("sResult", message);
        return bestSignal;
}

public void addNewAccessPoint(ScanResult scanResult){

    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = '\"' + scanResult.SSID + '\"';
    //wc.preSharedKey  = "\"password\"";
    wc.hiddenSSID = true;
    wc.status = WifiConfiguration.Status.ENABLED;        
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    int res = mainWifi.addNetwork(wc);
    Log.d("WifiPreference", "add Network returned " + res );
    boolean b = mainWifi.enableNetwork(res, false);        
    Log.d("WifiPreference", "enableNetwork returned " + b );

}

When I try to use addNewAccessPoint(ScanResult scanResult) it just adds another AP to the list in the settings application with the same name as the one with the best signal, so I end up with loads of duplicates and not actually attaching to them.

Can anyone point me in the direction of a better solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

零時差 2024-09-08 18:54:30

只需更改

boolean b = mainWifi.enableNetwork(res, false);

boolean b = mainWifi.enableNetwork(res, true); 

Simply change

boolean b = mainWifi.enableNetwork(res, false);

to

boolean b = mainWifi.enableNetwork(res, true); 
剩一世无双 2024-09-08 18:54:30

更切中你的问题。首先,您要确定具有最佳信号强度的扫描结果。获得此信息后,您还应该获取设备上已有的 WiFi 配置列表,并确保设备尚未配置信号最强的扫描结果。如果是,只需启用它,如果不是,则按原样创建一个新的。这将帮助您避免重复的配置。

private int findExistingNetworkConfig(String ssid) {
    if (ssid != null && !ssid.isEmpty()) {
        WifiManager wifiManager = (WifiManager) mContextRef.get()
                .getSystemService(Context.WIFI_SERVICE);
        for (WifiConfiguration wifiConfig : wifiManager
                .getConfiguredNetworks()) {
            if (ssid.equals(wifiConfig.SSID)) {
                return wifiConfig.networkId;
            }
        }
    }
    // Didn't find a matching network ssid
    return -1;
}

是的,启用网络时请务必使用“true”参数。这将有助于确保您连接到所需的网络。

wifiManager.enableNetwork(mNetID, true);

More to the point of your question. First you are determining the scan result with the best signal strength. Once you have that, you should also get the list of wifi configurations already on the device and ensure that the scan result with the strongest signal is not already configured with the device. If it is, simply enable it, if not, create a new one as you are. This will help you avoid duplicate configs.

private int findExistingNetworkConfig(String ssid) {
    if (ssid != null && !ssid.isEmpty()) {
        WifiManager wifiManager = (WifiManager) mContextRef.get()
                .getSystemService(Context.WIFI_SERVICE);
        for (WifiConfiguration wifiConfig : wifiManager
                .getConfiguredNetworks()) {
            if (ssid.equals(wifiConfig.SSID)) {
                return wifiConfig.networkId;
            }
        }
    }
    // Didn't find a matching network ssid
    return -1;
}

And yes, be sure to use the 'true' parameter when enabling networks. This will help ensure you connect to the network you intend.

wifiManager.enableNetwork(mNetID, true);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文