如何在android中连接wifi

时间:2015-07-08 16:42:03

标签: java android

我是Android应用程序开发的新生,目前我做了Android Wifi连接代码以实现连接。应用程序显示可用的连接,但我无法连接到特定的wifi连接。 / p>

以下是我从搜索中获得的一个连接,我可以在我的大学场所看到很多这种类型的连接。

Ex:能力[WPA2-PSK CCMP] [WPS] [ESS],等级:-37,频率2412时间戳:9103895476

你可以帮我解决这个问题,并正确连接到可用的连接。此外,我决定实施Wifi ON / OFF按钮,并没有明确的想法实现这个..

以下是我的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);  
    }

}

以下是我的清单代码

<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" />

1 个答案:

答案 0 :(得分:2)

第一步是确定接入点的加密类型。为此,您可以参考my other answer here

以下是可用于检查特定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;
}   

然后,一旦确定用户想要连接到哪个接入点,就需要提示他们输入正确的凭据,然后使用正确的身份验证配置设备以连接到所选的接入点(SSID)。 / p>

参考my other answer about this以及this questionthis fairly complete guide

以下是我从其他答案中获得的工作和测试代码:

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

连接到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;
    }
}

然后,一旦您在设备上配置了多个SSID,如果您的应用的用户想要强制连接到一个特定的SSID并且范围内有多个SSID,那么您将遇到另一个问题。您需要禁用用户不想连接的SSID,并启用用户选择连接的SSID。 您可以参考my other answer about this here

请注意,此示例代码仅适用于范围内两个AP的情况,对于两个以上的范围,您需要禁用所有其他已配置的SSID以强制连接到一个SSID。

以下是解决此问题的一般想法:

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