简体   繁体   中英

How to connect wifi in android

I'm new student for android app developing, Currently I did the Android Wifi connection code in order to make the connectivity.The app is showing the available connections but I cannot possible to connect in to specific wifi connections.

Below is the one connectivity when i get from searching and i can see lot of these type of connections in my university premises.

Ex: capabilities [WPA2-PSK CCMP][WPS][ESS],level:-37,freequency 2412 timestamp: 9103895476

could you please help me to overcome this problem and connect correctly to available connections. Also i have decide to implement Wifi ON/OFF button and didnt have clear idea for this implementation..

Below is my Java code

TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();

public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.activity_wifi_connections);
   mainText = (TextView) findViewById(R.id.mainText);

   // Initiate wifi service manager
   mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

   // Check for wifi is disabled
   if (mainWifi.isWifiEnabled() == false)
        {   
            // If wifi disabled then enable it
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            mainWifi.setWifiEnabled(true);
        } 

   // wifi scaned value broadcast receiver 
   receiverWifi = new WifiReceiver();

   // Register broadcast receiver 
   // Broacast receiver will automatically call when number of wifi connections changed
   registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
   mainWifi.startScan();
   mainText.setText("Starting Scan...");
}

public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 0, 0, "Refresh");
    return super.onCreateOptionsMenu(menu);
}

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    mainWifi.startScan();
    mainText.setText("Starting Scan");
    return super.onMenuItemSelected(featureId, item);
}

protected void onPause() {
    unregisterReceiver(receiverWifi);
    super.onPause();
}

protected void onResume() {
    registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    super.onResume();
}

// Broadcast receiver class called its receive method 
// when number of wifi connections changed

class WifiReceiver extends BroadcastReceiver {

    // This method call when number of wifi connections changed
    public void onReceive(Context c, Intent intent) {

        sb = new StringBuilder();
        wifiList = mainWifi.getScanResults(); 
        sb.append("\n        Number Of Wifi connections :"+wifiList.size()+"\n\n");

        for(int i = 0; i < wifiList.size(); i++){

            sb.append(new Integer(i+1).toString() + ". ");
            sb.append((wifiList.get(i)).toString());
            sb.append("\n\n");
        }

        mainText.setText(sb);  
    }

}

Below is my manifest code

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.androidexample.wificonnections.WifiConnections"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

The first step is determining what type of encryption the Access Point has. For that, you can reference my other answer here .

Here is the code you could use to check the encryption type of a particular SSID:

public String getEncryptionType(String ssid){

    String encryptType = "";
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<ScanResult> networkList = wifi.getScanResults();

    if (networkList != null) {
        for (ScanResult network : networkList)
        {
            //check if current connected SSID
            if (ssid.equals(network.SSID)){
                //get capabilities of current connection
                String Capabilities =  network.capabilities;
                Log.d (TAG, network.SSID + " capabilities : " + Capabilities);

                if (Capabilities.contains("WPA2")) {
                    encryptType = "WPA2";
                }
                else if (Capabilities.contains("WPA")) {
                    encryptType = "WPA";
                }
                else if (Capabilities.contains("WEP")) {
                    encryptType = "WEP";
                }
            }
        }

    }
    return encryptType;
}   

Then, once you determine which Access Point the user wants to connect to, you will need to prompt them for the correct credentials, and then configure the device with the correct authentication to connect to the Access Point (SSID) chosen.

Reference my other answer about this and also this question and also this fairly complete guide .

Here is code that I got working and tested taken from my other answer:

For connecting to WEP:

public boolean ConnectToNetworkWEP( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes
        conf.wepKeys[0] = "\"" + password + "\""; //Try it with quotes first

        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.OPEN);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.SHARED);


        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int networkId = wifiManager.addNetwork(conf);

        if (networkId == -1){
            //Try it again with no quotes in case of hex password
            conf.wepKeys[0] = password;
            networkId = wifiManager.addNetwork(conf);
        }

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

        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}

For connecting to WPA2:

public boolean ConnectToNetworkWPA( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes

        conf.preSharedKey = "\"" + password + "\"";

        conf.status = WifiConfiguration.Status.ENABLED;
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

        Log.d("connecting", conf.SSID + " " + conf.preSharedKey);

        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.addNetwork(conf);

        Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);



        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();
                Log.d("re connecting", i.SSID + " " + conf.preSharedKey);

                break;
            }
        }


        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}

Then, once you have multiple SSIDs configured on the device, if the user of your app wants to force a connection to one particular SSID and there are more than one in range, you'll run into another problem. You will need to disable the SSIDs that the user does not want to connect to, and enable the SSID that the user chooses to connect to. You can reference my other answer about this here .

Note that this sample code is just for the case of two APs in range, for more than two in range you would need to disable all other configured SSIDs in order to force a connection to one SSID.

Here's the general idea for solving this issue:

public void connectToNetwork(String ssid){

    WifiInfo info = mWifiManager.getConnectionInfo(); //get WifiInfo
    int id = info.getNetworkId(); //get id of currently connected network

    for (WifiConfiguration config : configurations) {
        // If it was cached connect to it and that's all
        if (config.SSID != null && config.SSID.equals("\"" +ssid + "\"")) {
            // Log
            Log.i("connectToNetwork", "Connecting to: " + config.SSID);

            mWifiManager.disconnect();

            mWifiManager.disableNetwork(id); //disable current network

            mWifiManager.enableNetwork(config.networkId, true);
            mWifiManager.reconnect();
            break;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM