3
votes

I want to connect to hardware by wifi. I use wifiManager for connecting but in real device if SSID and password is not saved, i can't connect to SSID programmatically and send or receive any data. If SSID and password is remembered in device, so my codes works well.

here is my code for connect to 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();


    }

and code for send data works well if wifi is connected

                    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

1 Answers

0
votes

Did you add the correct permission?

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