0

我创建了简单的应用程序来检测和连接到其他 wifi 设备。我可以连接其他设备,但无法使用已连接的 wifi 连接互联网。我想使用这个连接的 wifi 进行浏览。

我的连接代码是:

    public boolean connectToNetwork(String sBSSID, int iSecurityType,
        String sSecurityKey, String sSSID) {
    iSecurityType = 1;
    // Get context variable
    Context tmpContext = getApplicationContext();
    // getContexteApplication();
    // And WIFI manager object
    WifiManager tmpManager = (WifiManager) tmpContext
            .getSystemService(android.content.Context.WIFI_SERVICE);
    // Init variable to process current WIFI settings
    WifiConfiguration tmpConfig;
    // Checks if that WIFI network we want to connect to is not already
    // known

    // Retrieves a list of all configured networks
    List<WifiConfiguration> listConfig = tmpManager.getConfiguredNetworks();
    tmpConfig = new WifiConfiguration();
    // loop on it
    if (listConfig != null) {
        for (int i = 0; i < listConfig.size(); i++) {
            // Get the element config in the processing variable
            tmpConfig = listConfig.get(i);
            // Checks if already there
            if (tmpConfig.BSSID != null) {
                if (tmpConfig.BSSID.equalsIgnoreCase(sBSSID)) {
                    // found: returns the result of trying to enabling it
                    return tmpManager.enableNetwork(tmpConfig.networkId,
                            true);
                }
            }
        }
    }
    // It's a new network, we need to set it up
    // Creates a new WIFIconfiguration object

    // Set the needed information
    tmpConfig.BSSID = sBSSID;
    tmpConfig.SSID = sSSID;
    tmpConfig.priority = 1;
    switch (iSecurityType) {
    // WPA
    case 1:
        tmpConfig.preSharedKey = sSecurityKey;
        break;
    // WEP
    case 2:
        tmpConfig.wepKeys[0] = sSecurityKey;
        tmpConfig.wepTxKeyIndex = 0;
        break;
    // None
    case 3:
        break;
    }
    // Connection status
    tmpConfig.status = WifiConfiguration.Status.ENABLED;
    // Adds the new configuration
    int netId = tmpManager.addNetwork(tmpConfig);
    // Attempt to connect to network, return result
    return tmpManager.enableNetwork(netId, true);
}
4

1 回答 1

0

您必须授予您的应用互联网权限。将以下内容添加到您的清单中:

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

有关可用权限的列表,请参见此处。

于 2013-07-19T08:37:15.347 回答