我正在为物联网设备编写Android应用程序。我必须给设备WiFi用户名和密码,所以我使用Android应用程序来做到这一点。我有以下代码,但似乎总是连接到网络天气或没有给出正确的密码。
这是我在手机连接的同一个AP上测试的。
所需的操作是
断开与当前AP的连接 - >尝试使用给定的凭据进行连接 - >重新连接到原始网络。
正确验证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;
}
}
答案 0 :(得分:4)
您应该注册到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;
}
}
答案 1 :(得分:0)
您可能不需要扫描可用的wifi网络,您可以轻松地执行以下操作:按照
public static void connectToWifi(Activity activity, String ssid, String password) {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", password);
WifiManager wifiManager = (WifiManager) activity.getSystemService(WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
答案 2 :(得分:0)
只是检查它就像那样
public static boolean isConnectingToInternet(Context context){
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info[] = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}catch (Exception e){}
return false;
}