在WifiManager.reconnect()之后需要等待

时间:2014-07-18 17:31:17

标签: android wifimanager

我使用WifiManager将特定应用程序连接到特定的Wifi SSID。 我遇到了一个奇怪的问题但是因为我似乎是唯一一个遇到这个问题的人,我想知道它是不是因为我在genymotion模拟器上测试它....

问题很简单,它在调试中工作,而不是在正常运行中。

实际上是对responseCode = httpConnection.getResponseCode()的调用; 代码的一部分就是这个:

            ....
            List<WifiConfiguration> list = wifi.getConfiguredNetworks();
            for( WifiConfiguration i : list ) {
                if(i.SSID != null && (i.SSID.equals("\"" + site.getWifiSSID() + "\"") == false)) {

                     wifi.disconnect();
                     wifi.enableNetwork(conf.networkId, true);
                     wifi.reconnect();               

                     break;
                 }
             }
             String verif = site.getWifiSSID();
             // I tried this but the wifi is enabled in fact. It just seems to be not ready
             for (int i = 0; (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) && i < 300; i++) {
                 try {
                    Thread.sleep(500);
                 } catch(InterruptedException e) {
                    Log.d("2ndGuide", "InterruptException" + e);
                 }
             }
        }

        try {
            int responseCode = 0, i = 0;
            url = new URL(site.getDescriptionFileUrl());

            // Here is the stupid code I need to add to get it working!!!
            try {   
                Thread.sleep(500);
            } catch(InterruptedException e) {
                Log.d("2ndGuide", "InterruptException" + e);
            }
            // Création d'une connection HTTP à une URL
            URLConnection connection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection)connection;
            responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                 ...
            }
        }
        catch (MalformedURLException e) {
            Log.d("2ndGuide", "Malformed URL Exception." + e);

        } 
        catch (IOException e) {
            Log.d("2ndGuide", "IO Exception." + e);
        }
        // The call to getRespnseCode() exits here with a return value of 0
        Log.d("2ndGuide", mActivity.getResources().getString(R.string.label_messageAlertCnfBadUrl));
        return -6;

看来,在调用reconnect()后,wifi无法立即使用。

为什么不呢,但我没有发现任何关于它的警告以及任何等待它可以使用的机制! 肯定有一些我想念的东西!

此致 阿兰

0 个答案:

没有答案