在我的应用程序中启用了wifi连接但无法浏览

时间:2013-07-19 08:13:19

标签: android android-wifi

我创建了简单的应用程序来检测并连接到其他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);
}

1 个答案:

答案 0 :(得分:0)

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

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

请参阅here以获取可用权限列表。

相关问题