首页 文章

无法连接到WiFi网络

提问于
浏览
1

我是Android开发新手,并尝试使用Android SDK连接到WiFi网络 . 断开连接的代码工作正常,但重新连接失败 . 这是我的代码

try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes
        conf.wepKeys[0] = password;  //WEP password is in hex, we do not need to surround it with quotes.
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 

        WifiManager wifiManager = (WifiManager)ba.applicationContext.getSystemService(Context.WIFI_SERVICE);
        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) {

        throw ex;
    }

我将此代码包装在一个jar文件中,我在不同的应用程序中使用它 . 当我调用此方法并尝试使用SSID和密码连接到WEP网络时,我继续收到以下错误:

android.system.ErrNoException:recvfrom failed:ETIMEDOUT(连接超时) .

该错误确实告诉某处存在连接超时,但我无法解决这个问题以修复我的代码 . 我可以为代码引入任何指针和更改以使其工作?

Paritosh

1 回答

  • 0

    连接信息可以异步到达,因此您无法在提到的代码中知道连接是否成功 . 您可以尝试实现BroadcastReceiver,它获取wifi连接的信息 .

    public class ConnectivityChangedReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo[] netInf = conMgr.getAllNetworkInfo();
    
            for (NetworkInfo inf : netInf) {
                if (inf.getTypeName().contains("wifi")) {
                    if (inf.isConnected()) {
                        Toast.makeText(context, "Connected to Wifi", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "Could not connect to wifi", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
    

    然后,在您的Android清单中,您应该将其声明为接收器,如下所示:

    <receiver android:name=".YourPackageName.ConnectivityChangedReceiver" >
        <intent-filter>
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
            </intent-filter>
    </receiver>
    

    我现在只是自己尝试这个,但我认为这是这个问题的正确解决方法,因为Wifimanager.reconnect()并没有真正将我连接到配置的网络 . 祝你好运 .

相关问题