gpt4 book ai didi

android - 如何将android设备连接到具有特定SSID的wifi

转载 作者:行者123 更新时间:2023-12-05 00:07:12 27 4
gpt4 key购买 nike

我想通过 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();

最佳答案

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

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

关于android - 如何将android设备连接到具有特定SSID的wifi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25142697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com