Search code examples
javaandroidwifiandroid-wifiwifimanager

Android connect to Wifi programmatically if wifi name match


I would like to build an app, that checks all the available WiFi networks,

If a network's SSID matches a search key then connect to that network, if two networks match then connect to the one with the higher signal strength.

e.g. SearchKey = "Open";

here is the code to check check all the wifi names :

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

Then I would need to

Arrays.asList(mItems).contains("Open")

I am stuck here, How to do a proper check if the keyword "Open" exits, if so, then get the whole name and use below. ?

online sample how to conenct.

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

UPDATE CODE ------------------------------ - --------------------------------- - -- ---------------------------------------

How to check, This works But Now I need to implement Search by signal strength

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

Now how can I query my :

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

=== Now my question is how to the SSID name from mItems ? Thanks guys for your help.


Solution

  • Here is a snippet for the same:

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