其他分享
首页 > 其他分享> > android-无法连接到WiFi网络

android-无法连接到WiFi网络

作者:互联网

我是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 (Connection timed out).

该错误确实表明某处存在连接超时,但是我无法弄清楚该错误来修复我的代码.我可以在代码中引入任何指针和更改以使其工作?

Paritosh

解决方法:

连接信息可以异步到达,因此无论您是否成功连接,您都无法在上面提到的代码中知道.您可以尝试实现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()并未真正将我连接到配置的网络.祝你好运.

标签:android,android-wifi,wifimanager
来源: https://codeday.me/bug/20191014/1912031.html