如何使用特定的SSID将Android设备连接到wifi

时间:2014-08-05 15:29:55

标签: android wifi wifimanager

我想通过wifi连接到硬件。我使用wifiManager连接但在实际设备中如果没有保存SSID和密码,我无法以编程方式连接到SSID并发送或接收任何数据。如果在设备中记住SSID和密码,那么我的代码运行良好。

这是我连接到SSID的代码

private void connect2SSIDWifi() throws Exception{


        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifi.getConnectionInfo();


        try{     
        if(wifiInfo.getSSID().equals(publicClass.ssid)) return; 
         }catch(Exception ex){}
         try {
                Thread.sleep(500);
            } catch (InterruptedException e) {}


         WifiConfiguration wc = new WifiConfiguration();
         wc.SSID = "\""+publicClass.ssid+"\"";
         wc.preSharedKey  = "\""+publicClass.ps+"\"";
         wc.hiddenSSID = true;
         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 netid = wifi.addNetwork(wc);
          wifi.enableNetwork(netid, true);
          wifi.reconnect();


    }

如果连接了wifi,发送数据的代码就可以正常工作

                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress(publicClass.ip, publicClass.port), 300);
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream())), true);
                    out.println(Packet);
                    Log.d("tag",Packet);
                    Toast.makeText(context, "sent", Toast.LENGTH_SHORT).show();
                    socket.close();

1 个答案:

答案 0 :(得分:0)

您是否添加了正确的权限?

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