在android中连接到wifi网络,如果密码不正确则返回

时间:2011-08-24 06:48:37

标签: android wifi connect

我想创建一个让用户连接到wifi网络的应用程序,但是我无法连接到网络

我目前的代码是:

    WifiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
    wifi.setWifiEnabled(true);
    WifiConfiguration wc = new WifiConfiguration();
    wifi.startScan();
    List<ScanResult> l=wifi.getScanResults();
    wc.SSID = l.get(NUMBER).SSID;
    post(wc.SSID);
    /*This is the bit that I think is failing, my network does not have these properties.. but I can't see how to get them from the Scan Result*/
    wc.preSharedKey  = "\"passw0rd123\"";
    wc.hiddenSSID = false;
    wc.status = WifiConfiguration.Status.ENABLED;        
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    int res = wifi.addNetwork(wc);
    post("add Network returned " + res);
    boolean b = wifi.enableNetwork(res, true);        
    post("enableNetwork returned " + b);

我认为这与设置(在我的评论之后)与我的网络配置不同,但我不知道如何从ScanResult获取这些设置..

编辑: 我还想知道它是否已正确连接。

2 个答案:

答案 0 :(得分:-1)

确保在AndroidManifest.xml文件中设置正确的权限

答案 1 :(得分:-1)

检查您的设备是否启用了WIFI,并在模拟器中记住是否检查

如果在点击警报时禁用了WIFI,您可以像这样显示Wifi设置页面

 WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

           if ((wifi.isWifiEnabled() == true)) {

      Toast.makeText(RegisterActivity.this,"MOBILE Is Connected TO WI-FI!",
              }

              else {

                AlertDialog.Builder WIFIOFF = new Builder(MyTestglobe.this);
                WIFIOFF.setCancelable(false);
                WIFIOFF.setTitle("Connection Error");
                WIFIOFF.setMessage(" Please Enable Your WIFI/INTERNET !");
                WIFIOFF.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
             startActivity(new Intent( Settings.ACTION_WIFI_SETTINGS));

                            }
                        });
                WIFIOFF.show();

            }

并在你的Manifest.xml中提供这些权限

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    
       <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
      <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>