Monday, January 19, 2015

Android Tip - Connecting to a Wireless Network Programmatically

If you want to programmatically set your Android device to connect to a particular wireless network, you can use the WifiConfiguration and WifiManager classes:

        EditText txtNetworkName = (EditText) 
            findViewById(R.id.txtNetworkName);
        EditText txtPassword = (EditText) 
            findViewById(R.id.txtPassword);

        WifiConfiguration wifiConfiguration = new 
            WifiConfiguration();
        wifiConfiguration.SSID = String.format("\"%s\"", 
            txtNetworkName.getText().toString());
        wifiConfiguration.preSharedKey = String.format("\"%s\"", 
            txtPassword.getText().toString());

        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        int netId = wifiManager.addNetwork(wifiConfiguration);

        if (wifiManager.isWifiEnabled()) { //---wifi is turned on---
            //---disconnect it first---
            wifiManager.disconnect();
        } else { //---wifi is turned off---
            //---turn on wifi---
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.enableNetwork(netId, true);
        wifiManager.reconnect();

The above code snippet connects to a WPA-secured wireless network. It first checks if WiFi is enabled, turn if on if it is not, and then connects to the specified network.

To do the above, you need the following permissions in your AndroidManifest.xml file:

    <!--you need this to check if wifi is enabled-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <!--you need this to use wifi to connect to a network-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

No comments: