简体   繁体   English

如何在android中连接wifi

[英]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. 我是Android应用程序开发的新生,目前我做了Android Wifi连接代码,以便建立连接。应用程序显示可用的连接,但我无法连接到特定的WiFi连接。

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 例如:能力[WPA2-PSK CCMP] [WPS] [ESS],等级:-37,频率2412时间戳: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.. 此外,我已决定实施Wifi ON / OFF按钮,并没有明确的想法这个实现..

Below is my Java code 下面是我的Java代码

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: 以下是可用于检查特定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. 然后,一旦确定用户想要连接到哪个接入点,您将需要提示他们输入正确的凭据,然后使用正确的身份验证配置设备以连接到所选的接入点(SSID)。

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: 要连接到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: 要连接到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. 然后,一旦您在设备上配置了多个SSID,如果您的应用程序的用户想要强制连接到一个特定的SSID并且范围内有多个SSID,那么您将遇到另一个问题。 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. 您需要禁用用户不想连接的SSID,并启用用户选择连接的SSID。 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. 请注意,此示例代码仅适用于范围内两个AP的情况,对于两个以上的范围,您需要禁用所有其他已配置的SSID以强制连接到一个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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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