praveen
praveen

Reputation: 23

Unable to connect to a specific Wifi network programmatically on Android

I want to design an app which shows a list of wifi networks available and connect to the network when it is selected. I have implemented the part showing the scan results. Now i want to connect to a particular network selected by the user from the list of scan results. Can anyone please tell me how to do this?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listview = (ListView) findViewById(R.id.listView);

    adapter = new ArrayAdapter
            (this, android.R.layout.simple_list_item_1);

    listview.setAdapter(adapter);

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    wifiReciever = new WiFiScanReceiver();


}

public void onToggleClicked(View view) {

    adapter.clear();

    ToggleButton toggleButton = (ToggleButton) view;

    if (wifiManager == null) {
        // Device does not support Wi-Fi
        Toast.makeText(getApplicationContext(), "Oop! Your device does not support Wi-Fi",
                Toast.LENGTH_SHORT).show();
        toggleButton.setChecked(false);

    } else {
        if (toggleButton.isChecked()) { // To turn on Wi-Fi
            if (!wifiManager.isWifiEnabled()) {

                Toast.makeText(getApplicationContext(), "Wi-Fi is turned on." +
                                "\n" + "Scanning for access points...",
                        Toast.LENGTH_SHORT).show();

                wifiManager.setWifiEnabled(true);

            } else {
                Toast.makeText(getApplicationContext(), "Wi-Fi is already turned on." +
                                "\n" + "Scanning for access points...",
                        Toast.LENGTH_SHORT).show();
            }
            wifiManager.startScan();

        } else { // To turn off Wi-Fi
            Toast.makeText(getApplicationContext(), "Wi-Fi is turned off.",
                    Toast.LENGTH_SHORT).show();
            wifiManager.setWifiEnabled(false);
        }
    }


}

class WiFiScanReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        //if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
        //    wifiScanResult = wifiManager.getScanResults();


        if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
            List<ScanResult> wifiScanResultList = wifiManager.getScanResults();
            for (int i = 0; i < wifiScanResultList.size(); i++) {
                ScanResult accessPoint = wifiScanResultList.get(i);
                //wifiScanList[i] = wifiScanResultList.get(i).SSID;
                String listItem = " Name: " + accessPoint.SSID +    " \n Mac: " + accessPoint.BSSID + "\n Signal Strenght: " + accessPoint.level+ "dBm";
                adapter.add(listItem);
                // }
                // }
                //listview.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, wifiScanList));


            }
        }


    }
}








@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(wifiReciever);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.wi_fi, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Upvotes: 2

Views: 8011

Answers (3)

SaadurRehman
SaadurRehman

Reputation: 660

The accepted answer will not work for Oreo+! We need to specify properly the wificonfig to connec to the specific Wifi network. I had the similar usecase which i did resolve using some common sense. The wifi which we are going to connect should be avialable right? This means that if we scan the wifi manager then in the List of ScanResult there should be the device with SSID == MySSID, In this matching scanResult we also have the security type possessed by the scanned item, that will help us to make a more specific WifiConfig for WPA2 and WEP, Make sense?

Okay so here we go step by step! 1. Create a Wifi manager instance, and call startScan on it like

mWifiManager.startScan()

, upon calling this the scanlist of the available devices is received through the BroadcastReceiver whose OnReceive should look like this:

if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> mScanResults = mWifiManager.getScanResults();
            for (ScanResult res :
                    mScanResults) {
                if (!isConnected && res.SSID.contains(networkSSID)) {
                    networkSSID = res.SSID;
                    connectthis(res);
                }
            }

2. The connect this method should look like this:

private void connectthis(ScanResult res) {
    Context context = getApplicationContext();
    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", res.SSID);
    wifiConfig.BSSID = res.BSSID;
    wifiConfig.priority = 40;
    if (res.capabilities.toLowerCase().contains("wep")) {
        wifiConfig.wepKeys[0] = String.format("\"%s\"", networkKey);
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    } else if (res.capabilities.toLowerCase().contains("wpa")) {
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wifiConfig.preSharedKey = String.format("\"%s\"", networkKey);
    }


    if (networkKey.equalsIgnoreCase(""))
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    WifiManager wifiManager = 
   (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    boolean isConfigured = false;
    List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
    for (WifiConfiguration i : list) {
        if (i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
            wifiManager.disconnect();
            wifiManager.enableNetwork(i.networkId, true);
            wifiManager.reconnect();
            isConfigured = true;
            break;
        }
    }
    //adding the network
    if (!isConfigured) {
        int netId = wifiManager.addNetwork(wifiConfig);
        wifiManager.saveConfiguration();
        wifiManager.disconnect();
        wifiManager.enableNetwork(netId, true);
    }
}

Hope it helps!

Upvotes: 4

Daniel Givoni
Daniel Givoni

Reputation: 743

fire up this method on each item selected from your listview:

  static public void ConnectToWiFi(String ssid ,String key,Context ctx) {

    WifiConfiguration wifiConfig = new WifiConfiguration();
    wifiConfig.SSID = String.format("\"%s\"", ssid);
    wifiConfig.preSharedKey = String.format("\"%s\"", key);
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(ctx.WIFI_SERVICE);
    int networkId = wifiManager.getConnectionInfo().getNetworkId();
    wifiManager.removeNetwork(networkId);
    wifiManager.saveConfiguration();
    //remember id
    int netId = wifiManager.addNetwork(wifiConfig);
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect();
}

enter the item's SSID and key/password and you can drop the Context if not needed.
good luck

Upvotes: 1

Itapu Vinay
Itapu Vinay

Reputation: 697

The below links will be a good starting point for you to understand android WiFi Manager and connecting to a particular network.

  1. How to connect to a specific WiFi network

  2. Create and manage WiFi Configurations

Hope this helps.

Upvotes: 0

Related Questions