gpt4 book ai didi

Android以编程方式测试wifi连接

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:47 26 4
gpt4 key购买 nike

我正在为 IoT 设备编写 Android 应用程序。我必须为设备提供 WiFi 用户名和密码,所以我使用 Android 应用程序来执行此操作。我有以下代码,但它似乎总是连接到网络天气或没有给出正确的密码。

我正在我的手机所连接的同一个 AP 上进行测试。

所需的操作是

Disconnect from current AP -> Attempt to connect using credentials given -> Reconnect to original network.

我需要采取哪些步骤才能正确验证 wifi 网络和密码?

代码:

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
for(ScanResult sr: wifiList){
if(sr.SSID.equals(ssid)){
if(sr.capabilities.contains("WEP")){
if(isNumeric(pass)){
conf.wepKeys[0] = pass ;
}else{
conf.wepKeys[0] = "\"" + pass + "\"";
}
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}else if(sr.capabilities.contains("PSK")){
conf.preSharedKey = "\""+ pass +"\"";
}else if(sr.capabilities.contains("EAP")){
wifiName.setError("EAP networks not supported");
//todo support EAP
}else{
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}

WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);

List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.equals(conf)) {
wifiManager.disconnect();
if(!wifiManager.enableNetwork(i.networkId, true)){
wifiPassword.setError("Incorrect Password");
wifiManager.reconnect();
return;
}else{
wifiManager.reconnect();
addUser(deviceSN, ssid, pass);
}
}
}

break;
}
}

最佳答案

您应该注册到 NETWORK_STATE_CHANGED_ACTION。

使用它,您可以获得WI-FI网络状态,您需要检查它是否达到连接状态。如果设备在超时后仍未连接,您可以认为连接失败。

另一个有用的接收器可能是 SUPPLICANT_STATE_CHANGED_ACTION。

public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {

NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

switch (info.getState()) {
case CONNECTING:
break;
case CONNECTED:
break;
case DISCONNECTING:
break;
case DISCONNECTED:
break;
case SUSPENDED:
break;
}
}

关于Android以编程方式测试wifi连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100631/

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